diff --git a/.gitignore b/.gitignore index b8a7398d0..187362488 100644 --- a/.gitignore +++ b/.gitignore @@ -21,3 +21,4 @@ deliverables/*/.idea /projects/fangjia-open/.idea *.idea* classes +**/sdklog/* diff --git a/Jenkinsfile b/Jenkinsfile index b8b0cf0b7..fe1323a0e 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -2,7 +2,7 @@ pipeline { agent any parameters { - choice(name: 'PROJECT_NAME', choices: ['fangjiabkoff', 'chafangtong', 'fangjia', 'fangjiapds', 'fangjiastatic', 'geluke'], description: '请选择å�‘布的项目') + choice(name: 'PROJECT_NAME', choices: ['chafangtong', 'fangjia', 'fangjiapds', 'fangjiastatic', 'geluke', 'fangjiaopen'], description: '请选择å�‘布的项目') } tools { jdk 'JDK8' @@ -17,7 +17,7 @@ pipeline { stage('Maven Build') { steps { script { - def projects = ['fangjiabkoff', 'chafangtong', 'fangjia', 'fangjiapds', 'fangjiastatic', 'geluke'] + def projects = ['fangjiabkoff', 'chafangtong', 'fangjia', 'fangjiapds', 'fangjiastatic', 'geluke', 'fangjiaopen'] for (def project : projects) { if (params.PROJECT_NAME == project) { dir("deliverables/${project}") { @@ -33,8 +33,8 @@ pipeline { stage('Docker Build') { steps { script { - def projects = ['fangjiabkoff', 'chafangtong', 'fangjia', 'fangjiapds', 'fangjiastatic', 'geluke'] - def imagesName = ['fangjiabkoff': 'fangjia-bkoff', 'chafangtong': 'chafangtong', 'fangjia': 'fangjia-coresite', 'fangjiapds': 'fangjia-pds', 'fangjiastatic': 'fangjia-static', 'geluke':"geluke"] + def projects = ['fangjiabkoff', 'chafangtong', 'fangjia', 'fangjiapds', 'fangjiastatic', 'geluke', 'fangjiaopen'] + def imagesName = ['fangjiabkoff': 'fangjia-bkoff', 'chafangtong': 'chafangtong', 'fangjia': 'fangjia-coresite', 'fangjiapds': 'fangjia-pds', 'fangjiastatic': 'fangjia-static', 'geluke':"geluke", 'fangjiaopen': 'fangjia-open'] for (def project : projects) { if (params.PROJECT_NAME == project) { dir("projects/${imagesName[project]}") { @@ -53,8 +53,8 @@ pipeline { stage('K8S Deploy') { steps { script { - def projects = ['fangjiabkoff', 'chafangtong', 'fangjia', 'fangjiapds', 'fangjiastatic', 'geluke'] - def k8s_config_map = ['fangjiabkoff': 'fangjia-bkoff', 'chafangtong': 'chafangtong', 'fangjia': 'fangjia-coresite', 'fangjiapds': 'fangjia-pds', 'fangjiastatic': 'fangjia-static', 'geluke':"geluke"] + def projects = ['fangjiabkoff', 'chafangtong', 'fangjia', 'fangjiapds', 'fangjiastatic', 'geluke', 'fangjiaopen'] + def k8s_config_map = ['fangjiabkoff': 'fangjia-bkoff', 'chafangtong': 'chafangtong', 'fangjia': 'fangjia-coresite', 'fangjiapds': 'fangjia-pds', 'fangjiastatic': 'fangjia-static', 'geluke':"geluke", 'fangjiaopen': 'fangjia-open'] for (def project : projects) { if (params.PROJECT_NAME == project) { dir("deliverables/k8s") { diff --git a/deliverables/k8s/fangjia-open.yaml b/deliverables/k8s/fangjia-open.yaml index 32ce4bb75..09660e137 100644 --- a/deliverables/k8s/fangjia-open.yaml +++ b/deliverables/k8s/fangjia-open.yaml @@ -1,4 +1,4 @@ -:apiVersion: apps/v1 +apiVersion: apps/v1 kind: Deployment metadata: name: fangjia-open @@ -37,20 +37,39 @@ spec: - containerPort: 8080 name: web protocol: TCP + # readinessProbe: + # httpGet: + # path: /k8s/readiness + # port: web + # initialDelaySeconds: 5 + # periodSeconds: 10 + # livenessProbe: + # httpGet: + # path: /k8s/liveness + # port: web + # initialDelaySeconds: 10 + # periodSeconds: 5 volumeMounts: - name: host-time mountPath: /etc/localtime - - name: nfs + - name: goojiaconfig mountPath: /home/goojia/goojiaconfig volumes: - name: host-time hostPath: path: /etc/localtime - - name: nfs - nfs: - path: /home/nfs_data/goojiaconfig - server: 192.168.0.18 + - name: goojiaconfig + cephfs: + monitors: + - 192.168.0.208:6789 + - 192.168.0.209:6789 + - 192.168.0.210:6789 + user: admin + path: /k8s/goojiaconfig + secretRef: + name: ceph-secret + readOnly: false --- apiVersion: v1 @@ -69,4 +88,4 @@ spec: ports: - port: 8080 targetPort: 8080 - nodePort: 38089 \ No newline at end of file + nodePort: 31088 \ No newline at end of file diff --git a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/ApiCountLogController.java b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/ApiCountLogController.java new file mode 100644 index 000000000..5b263ce18 --- /dev/null +++ b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/ApiCountLogController.java @@ -0,0 +1,84 @@ +package com.fangjia.bkoff.controllers; + +import com.alibaba.excel.util.DateUtils; +import com.fangjia.bkoff.model.ApiCountLogModel; +import com.fangjia.bkoff.model.ApiUserModel; +import com.fangjia.bkoff.model.JsonModel; +import com.fangjia.core.util.*; +import com.fangjia.dal.QueryParam; +import com.fangjia.dal.mongo.fangjia.model.ServerArea; +import com.fangjia.dal.mongo.model.ApiCountLog; +import com.fangjia.dal.mongo.model.ApiInvokeStatistical; +import com.fangjia.dal.mongo.model.ApiUserCfg; +import com.fangjia.dal.mongo.model.bkoff.BkoffUsers; +import com.fangjia.dal.mongo.open.model.ApiJsonViewConfig; +import com.fangjia.dal.mongo.open.model.ApiUserAuthority; +import com.fangjia.dal.mongo.open.model.OpenResource; +import com.fangjia.dal.mongo.tool.model.ApiCountCity; +import com.fangjia.dal.mongo.tool.model.ApiVisitCount; +import com.fangjia.dal.mongo.tool.model.OpenResourceCount; +import com.fangjia.dal.mongo.tool.model.OpenUriAnaly; +import com.fangjia.dal.sql.model.ApiUser; +import com.fangjia.dal.sql.model.User; +import com.fangjia.service.api.ApiUserCfgService; +import com.fangjia.service.mongo.bkoff.ApiInvokeStatisticalService; +import com.fangjia.service.mongo.bkoff.BkoffUsersService; +import com.fangjia.service.mongo.fangjia.ApiCountLogService; +import com.fangjia.service.mongo.fangjia.ServerAreaService; +import com.fangjia.service.open.*; +import com.fangjia.service.sql.ApiUserService; +import com.fangjia.service.sql.UserService; +import org.apache.commons.codec.digest.DigestUtils; +import org.apache.commons.lang.StringUtils; +import org.apache.poi.hssf.usermodel.*; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.json.JSONArray; +import org.sothis.core.util.CollectionUtils; +import org.sothis.core.util.Pager; +import org.sothis.web.mvc.ActionContext; +import org.sothis.web.mvc.annotation.Param; + +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.OutputStream; +import java.math.BigDecimal; +import java.net.URLEncoder; +import java.text.DecimalFormat; +import java.text.SimpleDateFormat; +import java.util.*; + + +/** + * apiÓû§¿ªÍ¨µÈ¹ÜÀícontroller + * + * @author + */ +public class ApiCountLogController { + private BkoffUsersService bkoffUsersService; + private ApiCountLogService apiCountLogService; + + public Object listAction(ApiCountLogModel model) { + Pager pager = model.getPager(30); + if (pager.getCurrentPage() > 100) { + pager.setCurrentPage(1); + } + List apiCountLogList = apiCountLogService.findApiCountLog(model.getUserId(), model.getUri(),pager); + model.setApiCountLogList(apiCountLogList); + pager.setTotalRows(apiCountLogList.size()); + model.setPager(pager); + return model; + } + public void setBkoffUsersService(BkoffUsersService bkoffUsersService) { + this.bkoffUsersService = bkoffUsersService; + } + + public void setApiCountLogService(ApiCountLogService apiCountLogService) { + this.apiCountLogService = apiCountLogService; + } +} diff --git a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/ApiUserController.java b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/ApiUserController.java index 54be64383..0b41a057d 100644 --- a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/ApiUserController.java +++ b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/ApiUserController.java @@ -9,8 +9,11 @@ import com.fangjia.bkoff.model.JsonModel; import com.fangjia.core.util.*; import com.fangjia.dal.QueryParam; import com.fangjia.dal.mongo.fangjia.model.ServerArea; +import com.fangjia.dal.mongo.model.ApiCountLog; import com.fangjia.dal.mongo.model.ApiInvokeStatistical; import com.fangjia.dal.mongo.model.ApiUserCfg; +import com.fangjia.dal.mongo.model.RegionBlock; +import com.fangjia.dal.mongo.model.bkoff.BkoffUsers; import com.fangjia.dal.mongo.open.model.ApiJsonViewConfig; import com.fangjia.dal.mongo.open.model.ApiUserAuthority; import com.fangjia.dal.mongo.open.model.OpenResource; @@ -21,7 +24,11 @@ import com.fangjia.dal.mongo.tool.model.OpenUriAnaly; import com.fangjia.dal.sql.model.ApiUser; import com.fangjia.dal.sql.model.User; import com.fangjia.service.api.ApiUserCfgService; +import com.fangjia.service.bo.ServerAreaBo; import com.fangjia.service.mongo.bkoff.ApiInvokeStatisticalService; +import com.fangjia.service.mongo.bkoff.BkoffUsersService; +import com.fangjia.service.mongo.fangjia.ApiCountLogService; +import com.fangjia.service.mongo.fangjia.RegionBlockService; import com.fangjia.service.mongo.fangjia.ServerAreaService; import com.fangjia.service.open.*; import com.fangjia.service.sql.ApiUserService; @@ -73,6 +80,10 @@ public class ApiUserController { private ApiInvokeStatisticalService apiInvokeStatisticalService; private ApiVisitCountService apiVisitCountService; private ApiCountCityService apiCountCityService; + private BkoffUsersService bkoffUsersService; + private ApiCountLogService apiCountLogService; + + private RegionBlockService regionBlockService; /** * ËùÓÐapiÓû§µÄÐÅϢչʾ @@ -89,7 +100,21 @@ public class ApiUserController { * @param ApiUser * :Óû§µÄappKey username¡¢µÈ×ÊÁÏ */ - List apiUsers = this.apiUserService.findApiUsersByParamsSortDate(null); + ArrayList queryParams = new ArrayList(); + if (model.getStatus() != null) { + queryParams.add(new QueryParam("status", model.getStatus())); + } else { + queryParams.add(new QueryParam("status", 0)); + } + if (model.getIsTest() != null) { + queryParams.add(new QueryParam("isTest", model.getIsTest())); + } else { + queryParams.add(new QueryParam("isTest", 0)); + } + if (model.getPurpose() != null) { + queryParams.add(new QueryParam("purpose", model.getPurpose())); + } + List apiUsers = this.apiUserService.findApiUsersByParamsSortDate(queryParams); List apiUserBoList = new ArrayList(); for (ApiUser apiUser : apiUsers) { User user = this.userService.findById(apiUser.getId()); @@ -113,7 +138,9 @@ public class ApiUserController { bo.setDeadTime(apiUser.getDeadTime()); bo.setManager(apiUser.getManager()); bo.setIsMonitor(apiUser.getIsMonitor()); - + bo.setIsMonitorStatistic(apiUser.getIsMonitorStatistic()); + bo.setIsMonitorUsed(apiUser.getIsMonitorUsed()); + bo.setIsWarnExpired(apiUser.getIsWarnExpired()); apiUserBoList.add(bo); } @@ -195,9 +222,14 @@ public class ApiUserController { apiUser.setDeadTime(model.getDeadTime()); apiUser.setManager(model.getManager()); apiUser.setIsMonitor(model.getIsMonitor()); + apiUser.setContact(model.getContact()); + apiUser.setPhone(model.getPhone()); + apiUser.setIsMonitorStatistic(model.getIsMonitorStatistic()); + apiUser.setIsMonitorUsed(model.getIsMonitorUsed()); + apiUser.setIsWarnExpired(model.getIsWarnExpired()); this.apiUserService.save(apiUser); // ÐÂÔöÓû§£¬Ä¬ÈϹÒÅÆ¼Û¸ÄΪĬÈÏÆÀ¹À¼Û - model.setPriceType("evaluate"); + model.setPriceType("2B"); modifyUserCfg(id, ApiUserCfg.ApiUserCfgKey.PRICE_TYPE, model.getPriceType()); if (model.getEvaluateRate() != null && model.getEvaluateRate() != 0) { ApiUserCfg apiUserCfg = new ApiUserCfg(); @@ -231,6 +263,9 @@ public class ApiUserController { bo.setDisplayName(user.getDisplayName()); bo.setIsTest(apiUser.getIsTest()); bo.setPurpose(apiUser.getPurpose()); + bo.setIsMonitorStatistic(apiUser.getIsMonitorStatistic()); + bo.setIsMonitorUsed(apiUser.getIsMonitorUsed()); + bo.setIsWarnExpired(apiUser.getIsWarnExpired()); bo.setSiteName(apiUser.getSiteName()); bo.setIp(apiUser.getIp()); bo.setCompany(apiUser.getCompany()); @@ -238,6 +273,8 @@ public class ApiUserController { bo.setDeadTime(apiUser.getDeadTime()); bo.setManager(apiUser.getManager()); bo.setIsMonitor(apiUser.getIsMonitor()); + bo.setContact(apiUser.getContact()); + bo.setPhone(apiUser.getPhone()); ApiUserCfg apiUserCfg_rate = apiUserCfgService.findByUserId(apiUser.getId(), ApiUserCfg.ApiUserCfgKey.EVALUATE_RATE); if (apiUserCfg_rate != null) { bo.setEvaluateRate((Double) apiUserCfg_rate.getCfgValue()); @@ -291,6 +328,11 @@ public class ApiUserController { dataApiUser.put("deadTime", model.getDeadTime()); dataApiUser.put("manager", model.getManager()); dataApiUser.put("isMonitor", model.getIsMonitor()); + dataApiUser.put("contact", model.getContact()); + dataApiUser.put("phone", model.getPhone()); + dataApiUser.put("isMonitorStatistic",model.getIsMonitorStatistic()); + dataApiUser.put("isMonitorUsed",model.getIsMonitorUsed()); + dataApiUser.put("isWarnExpired",model.getIsWarnExpired()); this.apiUserService.update(dataApiUser, userId); // ¸ü¸ÄÓû§ÃÜÂë // this.userService.updateById(user,userId); @@ -424,6 +466,7 @@ public class ApiUserController { ApiUserAuthority apiUserAuthority = apiUserAuthorityService.findByUserId(model.getUserId()); Map cityCreditMap = apiUserAuthority.getCityCreditMap(); model.setDisplayName(user.getDisplayName() == null ? "" : user.getDisplayName()); + model.setProvinceList(getProvinceList()); model.setCityFirstLetters(Arrays.asList(getCityFirstLetter())); List serverAreaList = serverAreaService.findAll();// Load³ÇÊÐÁбí if (StringUtils.isBlank(model.getType()) || "all".equals(model.getType())) {// ×Öĸ·Ö×éÁбí @@ -444,6 +487,19 @@ public class ApiUserController { } serverAreaLetterList.add(map); } + if (model.getType().equals(serverArea.getProvince())) { + Map map = new HashMap(); + if (null != cityCreditMap && cityCreditMap.get(serverArea.getDisplay()) != null) { + map.put("key0", serverArea); + java.text.DecimalFormat df = new java.text.DecimalFormat("######0.00"); + String rate = df.format(cityCreditMap.get(serverArea.getDisplay())); + map.put("key1", rate); + } else { + map.put("key0", serverArea); + map.put("key1", null); + } + serverAreaLetterList.add(map); + } } model.setServerAreaList(serverAreaLetterList); } @@ -586,7 +642,8 @@ public class ApiUserController { * @param AuthorityBo * :Óû§µÄappKey username¡¢µÈ×ÊÁÏ */ - List openResourceList = openResourceService.findAll(); + List queryParams = Arrays.asList(new QueryParam("pubStatus", 1)); + List openResourceList = openResourceService.findOpenResource(queryParams); List authorityBoList = new ArrayList(); ApiUserAuthority authority = apiUserAuthorityService.findByUserId(model.getUserId()); if (authority == null) { @@ -621,7 +678,6 @@ public class ApiUserController { AuthorityBo bo = new AuthorityBo(); BeanUtils.copyProperties(openResource, bo); if (authority != null) { - bo.setHasAuth(authority.getOpenResourseUris().contains(bo.getUri())); bo.setHasAuth(authority.getOpenResourseUris().contains(bo.getUri())); model.setSupportLatLng(authority.isSupportLatLng()); bo.setLimitCountMap(authority.getLimitCountMap()); @@ -677,6 +733,9 @@ public class ApiUserController { public Object saveAuthAction(ApiUserModel model, HttpServletRequest request) throws IllegalAccessException { + List openResourceList = openResourceService.findAll(); + Map apiMap = converMapData(openResourceList); + model.setViewType("json"); model.setViewParam("config", null); Long userId = model.getUserId(); @@ -690,6 +749,7 @@ public class ApiUserController { authority.setSupportLatLng(model.isSupportLatLng()); apiUserAuthorityService.save(authority); } else { + Map countMap = authority.getTotalCountMap(); if (model.getLimit() != null) { Map limitCountMap = authority.getLimitCountMap(); if (limitCountMap == null) { @@ -703,7 +763,37 @@ public class ApiUserController { if (totalCountMap == null) { totalCountMap = new HashMap(); } - totalCountMap.put(model.getUri(), model.getSum()); + Integer count = model.getSum(); + //Ôö¼Ó´ÎÊýÐÞ¸ÄÈÕÖ¾ + ApiCountLog apiCountLog = new ApiCountLog(); + if (countMap != null && countMap.containsKey(model.getUri())) { + String bkoffUserId = (String) ThreadLocalData.getInstance().get(ThreadLocalKey.UserId); + User user = userService.findById(userId); + BkoffUsers bkoffUser = bkoffUsersService.findBkoffUsersById(bkoffUserId); + apiCountLog.setUserId(userId); + apiCountLog.setUserName(user.getDisplayName()); + apiCountLog.setUri(model.getUri()); + apiCountLog.setUriName(apiMap.get(model.getUri())); + apiCountLog.setOperator(bkoffUser.getRealName()); + Integer oldCount = countMap.get(model.getUri()); + apiCountLog.setOldCount(oldCount); + apiCountLog.setNewCount(count); + if (count > oldCount) { + apiCountLog.setOperate("Ôö¼Ó" + (count - oldCount) + "´Î"); + } else if (oldCount > count) { + apiCountLog.setOperate("¼õÉÙ" + (oldCount - count) + "´Î"); + } + + apiCountLog.setOperateTime(new Date()); + // ´ÎÊý¸Ä±äÁËÔټǼ + if (!count.equals(oldCount)) { + apiCountLogService.save(apiCountLog); + } + } + totalCountMap.put(model.getUri(), count); + if (count == 0) { + totalCountMap.remove(model.getUri()); + } authority.setTotalCountMap(totalCountMap); } if (model.getIsCheckCount() != null) { @@ -1255,7 +1345,7 @@ public class ApiUserController { dataList.add(row); } - String dateStr ="("+ DateUtils.format(startDate, "yyyy/MM/dd") + "¡ª" + DateUtils.format(endDate, "yyyy/MM/dd") +")"; + String dateStr = "(" + DateUtils.format(startDate, "yyyy/MM/dd") + "¡ª" + DateUtils.format(endDate, "yyyy/MM/dd") + ")"; String fileName = "Óû§Õ˺ÅʹÓÃͳ¼Æ" + dateStr + ".xlsx"; // ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build(); String displayName = URLEncoder.encode(fileName, "UTF-8"); @@ -1265,10 +1355,10 @@ public class ApiUserController { Sheet sheet = workbook.createSheet("Óû§Õ˺ÅʹÓÃͳ¼Æ"); List head = Arrays.asList( "Óû§ID", "Õ˺Å", "ºÏͬµ½ÆÚʱ¼ä", "½Ó¿Ú", "½Ó¿ÚÃû³Æ", "Ê£ÓàʹÓôÎÊý", - "·ÃÎÊ´ÎÊý(½üÒ»ÖÜ)", "ÈÕ¾ù·ÃÎÊÁ¿(½üÒ»ÖÜ)","³É¹¦²¢ÓÐЧ(½üÒ»ÖÜ)", "³É¹¦²¢ÎÞЧ(½üÒ»ÖÜ)","ʧ°Ü´ÎÊý(½üÒ»ÖÜ)", - "·ÃÎÊ´ÎÊý(½üÒ»ÔÂ)", "ÈÕ¾ù·ÃÎÊÁ¿(½üÒ»ÔÂ)","³É¹¦²¢ÓÐЧ(½üÒ»ÔÂ)", "³É¹¦²¢ÎÞЧ(½üÒ»ÔÂ)","ʧ°Ü´ÎÊý(½üÒ»ÔÂ)", - "·ÃÎÊ´ÎÊý"+dateStr, "ÈÕ¾ù·ÃÎÊÁ¿"+dateStr,"³É¹¦²¢ÓÐЧ"+dateStr, "³É¹¦²¢ÎÞЧ"+dateStr,"ʧ°Ü´ÎÊý"+dateStr - ); + "·ÃÎÊ´ÎÊý(½üÒ»ÖÜ)", "ÈÕ¾ù·ÃÎÊÁ¿(½üÒ»ÖÜ)", "³É¹¦²¢ÓÐЧ(½üÒ»ÖÜ)", "³É¹¦²¢ÎÞЧ(½üÒ»ÖÜ)", "ʧ°Ü´ÎÊý(½üÒ»ÖÜ)", + "·ÃÎÊ´ÎÊý(½üÒ»ÔÂ)", "ÈÕ¾ù·ÃÎÊÁ¿(½üÒ»ÔÂ)", "³É¹¦²¢ÓÐЧ(½üÒ»ÔÂ)", "³É¹¦²¢ÎÞЧ(½üÒ»ÔÂ)", "ʧ°Ü´ÎÊý(½üÒ»ÔÂ)", + "·ÃÎÊ´ÎÊý" + dateStr, "ÈÕ¾ù·ÃÎÊÁ¿" + dateStr, "³É¹¦²¢ÓÐЧ" + dateStr, "³É¹¦²¢ÎÞЧ" + dateStr, "ʧ°Ü´ÎÊý" + dateStr + ); // ´´½¨±íÍ· Row headRow = sheet.createRow(0); for (int i = 0; i < head.size(); i++) { @@ -1875,6 +1965,15 @@ public class ApiUserController { "T", "W", "X", "Y", "Z"}; return cityFirstLetter; } + private List getProvinceList(){ + List provinces = Arrays.asList( + "ɽ¶«", "¸£½¨", "ºÓ±±", "ºÓÄÏ", "ºþ±±", "ºþÄÏ", "½­Î÷", "º£ÄÏ", + "ºÚÁú½­", "ÉÂÎ÷", "¹óÖÝ", "н®", "½­ËÕ", "°²»Õ", "Î÷²Ø", + "¼ªÁÖ", "ɽÎ÷", "¸ÊËà", "ÄþÏÄ", "ËÄ´¨", "Õã½­", "¹ãÎ÷", + "ÔÆÄÏ", "ֱϽÊÐ", "ÄÚÃɹÅ", "ÁÉÄþ", "¹ã¶«", "Çຣ" + ); + return provinces; + } private Map> getCountByUri(List apiInvokeStatisticalList) { @@ -2032,4 +2131,144 @@ public class ApiUserController { model.setViewParam("location", "/apiUser/list"); return model; } + + private Map> splitCityInProvince(List allCitys) { + if (CollectionUtils.isEmpty(allCitys)) { + return Collections.emptyMap(); + } + List regionBlocks = regionBlockService.getRegionBlockList(); + Map> regionMap = new TreeMap>(); + for (RegionBlock regionBlock : regionBlocks) { + List regionBlockList = regionMap.get(regionBlock.getCity()); + if (regionBlockList == null) { + regionBlockList = new ArrayList(); + } + regionBlockList.add(regionBlock); + regionMap.put(regionBlock.getCity(), regionBlockList); + } + Map> ret = new HashMap>(); + for (ServerAreaBo city : allCitys) { + + String province = ""; + if (city.getProvince() == null || city.getProvince() == "") { + province = null; + } else if (city.getProvince().equals("ÉϺ£") || city.getProvince().equals("±±¾©") || city.getProvince().equals("Ìì½ò") + || city.getProvince().equals("ÖØÇì")) { + province = "ֱϽÊÐ"; + } else { + province = city.getProvince(); + } + if (province != null) { + + List cityBoList = ret.get(province); + if (CollectionUtils.isEmpty(cityBoList)) { + cityBoList = new ArrayList(); + } + CityBo bo = new CityBo(); + BeanUtils.copyProperties(city, bo); + + List getRegionBlock = regionMap.get(city.getDisplay()); + + if (getRegionBlock != null) { + + for (int i = getRegionBlock.size() - 1; i >= 0; i--) { + try { + if (getRegionBlock.get(i).getRegionType() != null && getRegionBlock.get(i).getRegionType() != 2) { + getRegionBlock.remove(i); + } + } catch (Exception e) { + e.printStackTrace(); + } + + } + + } + bo.setCityRegion(getRegionBlock); + cityBoList.add(bo); + ret.put(province, cityBoList); + } + } + return ret; + } + + public void setBkoffUsersService(BkoffUsersService bkoffUsersService) { + this.bkoffUsersService = bkoffUsersService; + } + + public void setApiCountLogService(ApiCountLogService apiCountLogService) { + this.apiCountLogService = apiCountLogService; + } + + public void setRegionBlockService(RegionBlockService regionBlockService) { + this.regionBlockService = regionBlockService; + } + + public class CityBo { + private String id; + private String display; + private String spell; + private String name; + private List cityRegion; + private int haveDistrict; // 0:ûÓÐ £¬ > 0:ÓÐ + private Map cityRegionHaveDistrict; // ÇøÓòÓÐÎÞÐ¡ÇøÍ³¼Æ 0£ºÃ»ÓÐ + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getDisplay() { + return display; + } + + public void setDisplay(String display) { + this.display = display; + } + + public String getSpell() { + return spell; + } + + public void setSpell(String spell) { + this.spell = spell; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getCityRegion() { + return cityRegion; + } + + public void setCityRegion(List cityRegion) { + this.cityRegion = cityRegion; + } + + public int getHaveDistrict() { + return haveDistrict; + } + + public void setHaveDistrict(int haveDistrict) { + this.haveDistrict = haveDistrict; + } + + public Map getCityRegionHaveDistrict() { + return cityRegionHaveDistrict; + } + + public void setCityRegionHaveDistrict(Map cityRegionHaveDistrict) { + this.cityRegionHaveDistrict = cityRegionHaveDistrict; + } + + } + + } diff --git a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/DevelopmentZoneController.java b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/DevelopmentZoneController.java index 8306117fe..036ffc89d 100644 --- a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/DevelopmentZoneController.java +++ b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/DevelopmentZoneController.java @@ -3,9 +3,11 @@ package com.fangjia.bkoff.controllers; import com.fangjia.bkoff.model.DevelopmentZoneModel; import com.fangjia.bkoff.model.JsonModel; import com.fangjia.bkoff.model.LatlngPolygonModel; +import com.fangjia.bkoff.util.ExcelUtils; import com.fangjia.core.util.GeoUtils; import com.fangjia.core.util.ThreadLocalData; import com.fangjia.core.util.ThreadLocalKey; +import com.fangjia.dal.QueryParam; import com.fangjia.dal.mongo.model.DevelopmentZone; import com.fangjia.dal.mongo.model.LatlngPolygon; import com.fangjia.dal.mongo.model.StatsIndex; @@ -13,9 +15,19 @@ import com.fangjia.dal.mongo.model.bkoff.BkoffUsers; import com.fangjia.service.mongo.bkoff.BkoffUsersService; import com.fangjia.service.mongo.fangjia.DevelopmentZoneService; import com.fangjia.service.mongo.fangjia.LatlngPolygonService; +import com.mashape.unirest.http.HttpResponse; +import com.mashape.unirest.http.Unirest; +import com.mashape.unirest.http.exceptions.UnirestException; import org.apache.commons.lang.StringUtils; +import org.json.JSONException; +import org.json.JSONObject; import org.sothis.core.util.Pager; +import org.sothis.web.mvc.ActionContext; +import javax.servlet.http.HttpServletRequest; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; import java.util.*; import static com.fangjia.core.util.GeoUtils.LAT; @@ -33,9 +45,9 @@ public class DevelopmentZoneController { if (pager.getCurrentPage() > 100) { pager.setCurrentPage(1); } - long countDev = developmentZoneService.countDev(model.getProvince(), model.getName(), model.getLevel()); + long countDev = developmentZoneService.countDev(model.getProvince(), model.getCityName1(), model.getName(), model.getLevel(), model.getOperateResult()); pager.setTotalRows((int) countDev); - List developmentZones = developmentZoneService.findDevelopmentZone(model.getProvince(), model.getName(), model.getLevel(), pager); + List developmentZones = developmentZoneService.findDevelopmentZone(model.getProvince(), model.getCityName1(), model.getName(), model.getLevel(), model.getOperateResult(), pager); model.setDevelopmentZoneList(developmentZones); model.setPager(pager); return model; @@ -59,6 +71,15 @@ public class DevelopmentZoneController { return model; } + public Object editFenceAction(DevelopmentZoneModel model) { + if (model.getId() == null) { + return model; + } + + model.setDevelopmentZone(developmentZoneService.findDevelopmentZone(model.getId())); + return model; + } + public Object deleteAction(LatlngPolygonModel model) { JsonModel ret = new JsonModel(); if (model.getId() == null) { @@ -110,6 +131,7 @@ public class DevelopmentZoneController { Object coordinates = convertGeoList(model.getBdShape()); shape.put("coordinates", coordinates); entity.setShape(shape); + entity.setOperateResult("ÒÑ´¦Àí"); } entity.setLevel(model.getLevel()); @@ -127,6 +149,8 @@ public class DevelopmentZoneController { entity.setUrl(StringUtils.isBlank(model.getUrl()) ? "" : model.getUrl()); entity.setCityName1(StringUtils.isBlank(model.getCityName1()) ? "" : model.getCityName1()); entity.setDistrict(StringUtils.isBlank(model.getDistrict()) ? "" : model.getDistrict()); + entity.setImgUrl(StringUtils.isBlank(model.getImgUrl()) ? "" : model.getImgUrl()); + entity.setOperateResult(StringUtils.isBlank(model.getOperateResult()) ? "" : model.getOperateResult()); //¼Ç¼²Ù×÷ÈËÔ± entity.setOperator(user.getRealName()); developmentZoneService.saveDevelopmentZone(entity); @@ -168,6 +192,7 @@ public class DevelopmentZoneController { Object coordinates = convertGeoList(model.getBdShape()); shape.put("coordinates", coordinates); udata.put("shape", shape); + udata.put("operateResult", "ÒÑ´¦Àí"); } if (StringUtils.isNotBlank(model.getAlias())) { String aliasString = model.getAlias().replaceAll(",", "£¬"); @@ -201,9 +226,15 @@ public class DevelopmentZoneController { if (StringUtils.isNotBlank(model.getCityName1())) { udata.put("cityName1", model.getCityName1()); } - if (StringUtils.isNotBlank(model.getDistrict())){ + if (StringUtils.isNotBlank(model.getDistrict())) { udata.put("district", model.getDistrict()); } + if (StringUtils.isNotBlank(model.getImgUrl())) { + udata.put("imgUrl", model.getImgUrl()); + } + if (StringUtils.isNotBlank(model.getOperateResult())){ + udata.put("operateResult", model.getOperateResult()); + } udata.put("createTime", new Date()); //¼Ç¼²Ù×÷ÈËÔ± udata.put("operator", user.getRealName()); @@ -259,5 +290,22 @@ public class DevelopmentZoneController { return gdLocationList; } + public Object uploadAction(DevelopmentZoneModel model) throws IOException, UnirestException, JSONException { + JsonModel ret = new JsonModel(); + Map data = new HashMap(); + File file = model.getFile(); + HttpResponse response = Unirest.post("http://open.fangjia.com/files/uploadGridFs") + .field("file", file) + .field("token", "F54F52381C49BB9EB4A33EB1B65604AE4B71A28AEE53518A94A2F360408B9056D57553931D15CE6DDE765562DAD286BA38E05A4CDAFC51C3D527A4959BF8E75A3B95DB7108FCEA340DDE61925616DB55118E1851E67D83EAD800460D100D6B667A4ED8EE67C8F7FB") + .asString(); + // »ñÈ¡·µ»ØµÄÁ´½Ó + JSONObject jsonResponse = new JSONObject(response.getBody()); + String link = jsonResponse.getJSONObject("result").getString("link"); + data.put("imgUrl", link); + data.put("msg", "ͼƬÉÏ´«³É¹¦"); + ret.setJsonModel(data); + return ret; + } + } diff --git a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/DistrictController.java b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/DistrictController.java index 080f08f51..a9c2fb20d 100644 --- a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/DistrictController.java +++ b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/DistrictController.java @@ -89,6 +89,7 @@ public class DistrictController { private DealPriceService dealPriceService; private AverageStatisticsService averageStatisticsService; + private static List distTypes = Arrays.asList("¶à²ã", "С¸ß²ã", "³¬¸ß²ã", "¸ß²ã", "»¨Ô°Ñó·¿", "ÀÏÑó·¿", "ËĺÏÔº"); private static List villaTypes = Arrays.asList("¶À¶°", "˫ƴ", "ÁªÅÅ", "µþ¼Ó"); private static List shopTypes = Arrays.asList("¶à²ã", "С¸ß²ã", "³¬¸ß²ã", "¸ß²ã", "¶À¶°", "˫ƴ", "ÁªÅÅ", "µþ¼Ó"); @@ -1178,7 +1179,7 @@ public class DistrictController { JsonModel model = new JsonModel(); - List districts = districtService.findByKey(city, region, name, cat); + List districts = districtService.findAllByNameAndCat(city, region, name, cat); boolean exist = false; if (StringUtils.isNotBlank(id)) { for (District district2 : districts) { @@ -2284,7 +2285,6 @@ public class DistrictController { data.put("markMap", markMap); data.put("modificationDate", new Date()); districtService.updateById(data, district.getId()); - //´´½¨¸üÐÂÈÎÎñ£¬ÓÃΪ¸üг£ÖÝÅ©ÉÌÐÐÊý¾Ý createJnTask(district.getId(), null); msg = "±£´æ³É¹¦ÁË£¡£¡£¡"; @@ -4211,5 +4211,4 @@ public class DistrictController { public void setAverageStatisticsService(AverageStatisticsService averageStatisticsService) { this.averageStatisticsService = averageStatisticsService; } - } diff --git a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/IndexStatsController.java b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/IndexStatsController.java index 3c555754b..394b7b033 100644 --- a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/IndexStatsController.java +++ b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/IndexStatsController.java @@ -34,13 +34,13 @@ public class IndexStatsController { SimpleDateFormat sdf=new SimpleDateFormat("yyyyMM"); yearmonth=sdf.format(date); } - List statsIndexs=statsIndexService.findAllStatsNocat(yearmonth,"district",model.getSource()); + List statsIndexs=statsIndexService.findAllStatsNocat(Integer.valueOf(yearmonth),"district",model.getSource()); Integer earliestMonth = statsIndexService.findEarliestMonth(null, null, model.getSource()); model.setEarliestMonth(earliestMonth.toString().substring(0, 4) + "-" + earliestMonth.toString().substring(4)); List newStats=new ArrayList(); List oldStats=new ArrayList(); - List shopStats=statsIndexService.findAllStatsNocat(yearmonth,"shop",model.getSource()); - List officeStats=statsIndexService.findAllStatsNocat(yearmonth,"office",model.getSource()); + List shopStats=statsIndexService.findAllStatsNocat(Integer.valueOf(yearmonth),"shop",model.getSource()); + List officeStats=statsIndexService.findAllStatsNocat(Integer.valueOf(yearmonth),"office",model.getSource()); if(statsIndexs!=null && statsIndexs.size()>0){ for(StatsIndex stat:statsIndexs){ StatsIndex newstat=new StatsIndex(); diff --git a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/OpenResourceController.java b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/OpenResourceController.java index 65eff39c5..ce5fc7904 100644 --- a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/OpenResourceController.java +++ b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/OpenResourceController.java @@ -2,10 +2,7 @@ package com.fangjia.bkoff.controllers; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; import com.fangjia.bkoff.model.JsonModel; import org.apache.commons.lang.StringUtils; @@ -42,6 +39,15 @@ public class OpenResourceController { } public Object doAddAction(OpenResourceModel model) { + List openResource = this.openResourceService.findOpenResource(null); + HashSet apiCodeSet = new HashSet(); + for (OpenResource resource : openResource) { + apiCodeSet.add(resource.getApiCode()); + } + if (model.getApiCode() != 0 && apiCodeSet.contains(model.getApiCode())){ + model.setMsg("APICodeÒÑ´æÔÚ"); + return model; + } if (!"doAdd".equals(model.getMethod())) { return model; } @@ -70,7 +76,9 @@ public class OpenResourceController { OpenResource r = new OpenResource(); r.setUri(uri); r.setName(name); + r.setApiCode(model.getApiCode()); r.setSaveResult(model.getSave_result()); + r.setPubStatus(model.getPubStatus() ? 1 : 0); r.setDescription(model.getDescription()); this.openResourceService.save(r); model.setMsg("Ìí¼Ó³É¹¦£¡"); @@ -80,6 +88,7 @@ public class OpenResourceController { public Object doChangeAction(OpenResourceModel model){ Map data = new HashMap(); data.put("saveResult",model.getSave_result()); + data.put("pubStatus",model.getPubStatus() ? 1 : 0); this.openResourceService.update(data,model.getId()); model.setMsg("±£´æ³É¹¦"); JsonModel model1 = new JsonModel(); @@ -105,6 +114,9 @@ public class OpenResourceController { if (StringUtils.isNotBlank(model.getDescription())) { data.put("description", model.getDescription()); } + if (0 != model.getApiCode()){ + data.put("apiCode",model.getApiCode()); + } List params = new ArrayList(); params.add(new QueryParam("uri", uri)); params.add(new QueryParam("name", name)); @@ -141,7 +153,7 @@ public class OpenResourceController { /** * ¸ñʽ»¯URI - * + * * @param uri * @return */ diff --git a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/fjtEvaluationController.java b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/fjtEvaluationController.java index cba98d594..e0d863383 100644 --- a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/fjtEvaluationController.java +++ b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/fjtEvaluationController.java @@ -422,9 +422,11 @@ public class fjtEvaluationController { row.createCell(6).setCellValue(bo.getCardId()); row.createCell(7).setCellValue(bo.getEmail()); row.createCell(8).setCellValue(allRoles.get(String.valueOf(bo.getRole()))); - row.createCell(9).setCellValue(bo.getCharge() + "·¿¶¹"); + row.createCell(9).setCellValue(""); + row.createCell(10).setCellValue(DateUtil.formatByPattern(bo.getDateCreated(),"yyyyÄêMMÔÂddÈÕ")); row.createCell(13).setCellValue(bo.getAccountChecker()); - row.createCell(14).setCellValue(DateUtil.formatByPattern(bo.getEvaluationDate(), "yyyyÄêMMÔÂddÈÕ")); + row.createCell(14).setCellValue(""); + row.createCell(17).setCellValue(DateUtil.formatByPattern(bo.getEvaluationDate(), "yyyyÄêMMÔÂddÈÕ")); } } diff --git a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/model/ApiCountLogModel.java b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/model/ApiCountLogModel.java new file mode 100644 index 000000000..61045484b --- /dev/null +++ b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/model/ApiCountLogModel.java @@ -0,0 +1,116 @@ +package com.fangjia.bkoff.model; + +import com.alibaba.fastjson.annotation.JSONField; +import com.fangjia.dal.mongo.model.ApiCountLog; +import com.fangjia.dal.mongo.model.Township; + +import java.util.Date; +import java.util.List; + +public class ApiCountLogModel extends BaseModel { + @JSONField(name = "id") + private String id; + + @JSONField(name = "user_id") + private Long userId; + @JSONField(name = "uri") + private String uri; + @JSONField(name = "user_name") + private String uriName; + @JSONField(name = "operate") + private String operate; + @JSONField(name = "operator") + private String operator; + + @JSONField(name = "operate_time") + private Date operateTime; + + // Ð޸ĴÎÊýǰ×Ü´ÎÊý + @JSONField(name = "old_count") + private Integer oldCount; + // Ð޸ĴÎÊýºóµÄ´ÎÊý + @JSONField(name = "new_count") + private Integer newCount; + private List apiCountLogList; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + public String getUri() { + return uri; + } + + public void setUri(String uri) { + this.uri = uri; + } + + public String getUriName() { + return uriName; + } + + public void setUriName(String uriName) { + this.uriName = uriName; + } + + public String getOperate() { + return operate; + } + + public void setOperate(String operate) { + this.operate = operate; + } + + public String getOperator() { + return operator; + } + + public void setOperator(String operator) { + this.operator = operator; + } + + public Date getOperateTime() { + return operateTime; + } + + public void setOperateTime(Date operateTime) { + this.operateTime = operateTime; + } + + public Integer getOldCount() { + return oldCount; + } + + public void setOldCount(Integer oldCount) { + this.oldCount = oldCount; + } + + public Integer getNewCount() { + return newCount; + } + + public void setNewCount(Integer newCount) { + this.newCount = newCount; + } + + public List getApiCountLogList() { + return apiCountLogList; + } + + public void setApiCountLogList(List apiCountLogList) { + this.apiCountLogList = apiCountLogList; + } +} + diff --git a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/model/ApiUserModel.java b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/model/ApiUserModel.java index ad264fe9a..a312fb80b 100644 --- a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/model/ApiUserModel.java +++ b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/model/ApiUserModel.java @@ -40,6 +40,16 @@ public class ApiUserModel extends BaseModel { private Map priceRatingMap; private Integer isMonitor; + private String contact; + + private String phone; + + private Integer isMonitorStatistic; + + private Integer isMonitorUsed; + + private Integer isWarnExpired; + public String getPriceType() { return priceType; } @@ -70,7 +80,7 @@ public class ApiUserModel extends BaseModel { private String type; private String citys;// spell private String unCheckCitys;// Ò³Ãæ·´Ñ¡µÄcity - private int status; + private Integer status; private String uri; private boolean hasAuth; private boolean supportLatLng; @@ -94,6 +104,8 @@ public class ApiUserModel extends BaseModel { private Integer isCheckCount; private String openResourseUrisMap; + + private List provinceList; public String getOpenResourseUrisMap() { return openResourseUrisMap; @@ -378,15 +390,15 @@ public class ApiUserModel extends BaseModel { this.limit = limit; } - public int getStatus() { + public Integer getStatus() { return status; } - public void setStatus(int status) { + public void setStatus(Integer status) { this.status = status; } - public String getCompany() { + public String getCompany() { return company; } @@ -615,4 +627,52 @@ public class ApiUserModel extends BaseModel { public void setIsMonitor(Integer isMonitor) { this.isMonitor = isMonitor; } + + public String getContact() { + return contact; + } + + public void setContact(String contact) { + this.contact = contact; + } + + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + + public Integer getIsMonitorStatistic() { + return isMonitorStatistic; + } + + public void setIsMonitorStatistic(Integer isMonitorStatistic) { + this.isMonitorStatistic = isMonitorStatistic; + } + + public Integer getIsMonitorUsed() { + return isMonitorUsed; + } + + public void setIsMonitorUsed(Integer isMonitorUsed) { + this.isMonitorUsed = isMonitorUsed; + } + + public Integer getIsWarnExpired() { + return isWarnExpired; + } + + public void setIsWarnExpired(Integer isWarnExpired) { + this.isWarnExpired = isWarnExpired; + } + + public List getProvinceList() { + return provinceList; + } + + public void setProvinceList(List provinceList) { + this.provinceList = provinceList; + } } diff --git a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/model/DevelopmentZoneModel.java b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/model/DevelopmentZoneModel.java index 54f85ab42..89565d57a 100644 --- a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/model/DevelopmentZoneModel.java +++ b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/model/DevelopmentZoneModel.java @@ -3,6 +3,7 @@ package com.fangjia.bkoff.model; import com.fangjia.dal.mongo.model.DevelopmentZone; import com.fangjia.dal.mongo.model.LatlngPolygon; +import java.io.File; import java.util.Date; import java.util.List; import java.util.Map; @@ -35,6 +36,12 @@ public class DevelopmentZoneModel extends BaseModel { private String cityName1; + private String imgUrl; + + private File file; + + private String operateResult; + public String getAlias() { return alias; } @@ -194,4 +201,29 @@ public class DevelopmentZoneModel extends BaseModel { public void setCityName1(String cityName1) { this.cityName1 = cityName1; } + + public String getImgUrl() { + return imgUrl; + } + + public void setImgUrl(String imgUrl) { + this.imgUrl = imgUrl; + } + + public File getFile() { + return file; + } + + public void setFile(File file) { + this.file = file; + } + + + public String getOperateResult() { + return operateResult; + } + + public void setOperateResult(String operateResult) { + this.operateResult = operateResult; + } } diff --git a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/model/OpenResourceModel.java b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/model/OpenResourceModel.java index 2f867b209..321e3f0ac 100644 --- a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/model/OpenResourceModel.java +++ b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/model/OpenResourceModel.java @@ -28,6 +28,9 @@ public class OpenResourceModel extends BaseModel { private Boolean save_result; private OpenResource or; + private Boolean pubStatus; + + private int apiCode; public String getExceptId() { return exceptId; @@ -116,4 +119,20 @@ public class OpenResourceModel extends BaseModel { public void setSave_result(Boolean save_result) { this.save_result = save_result; } + + public Boolean getPubStatus() { + return pubStatus; + } + + public void setPubStatus(Boolean pubStatus) { + this.pubStatus = pubStatus; + } + + public int getApiCode() { + return apiCode; + } + + public void setApiCode(int apiCode) { + this.apiCode = apiCode; + } } diff --git a/projects/fangjia-bkoff/src/main/resources/fangjia-bkoff.properties b/projects/fangjia-bkoff/src/main/resources/fangjia-bkoff.properties index 10f97fc98..99a3432fe 100644 --- a/projects/fangjia-bkoff/src/main/resources/fangjia-bkoff.properties +++ b/projects/fangjia-bkoff/src/main/resources/fangjia-bkoff.properties @@ -77,4 +77,4 @@ merchantno=10000469946 #appKey appKey=SQKK10000469946 #\u7EDF\u4E00\u9274\u6743\u7ED1\u5361\u8BF7\u6C42 -authbindcardreqUri=/rest/v1.0/paperorder/unified/pay +authbindcardreqUri=/rest/v1.0/paperorder/unified/pay \ No newline at end of file diff --git a/projects/fangjia-bkoff/src/main/webapp/apiCountLog/list.ftl b/projects/fangjia-bkoff/src/main/webapp/apiCountLog/list.ftl new file mode 100644 index 000000000..06fbad4d6 --- /dev/null +++ b/projects/fangjia-bkoff/src/main/webapp/apiCountLog/list.ftl @@ -0,0 +1,63 @@ +<#ftl attributes={"content_type":"text/html; charset=UTF-8"}> +<#compress> + + + + + 客户API次数æ“�作日志 + + + + + <#include "/common_js.ftl" /> + <#include "/layout/header.ftl" /> +
+
+
+ + + + + + +
+
+
+ 查询到${pager.totalRows!}�记录 + + + + + + + + + + + + + <#list apiCountLogList as it> + + + + + + + + + + + + +
用户ID用户昵称uriAPI�称�作原次数现次数�作人员修改日期
${it.userId!}${it.userName!}${it.uri!}${it.uriName!}${it.operate!}${it.oldCount!}${it.newCount!}${it.operator!}${it.operateTime!?string("yyyy-MM-dd HH:mm:ss")}
+ <#if pager??> + <@d_pager controller="apiCountLog" action="list" currentPage=pager.currentPage totalPages=pager.totalPages theme="full"/> + +
+
+ + + \ No newline at end of file diff --git a/projects/fangjia-bkoff/src/main/webapp/apiUser/add.ftl b/projects/fangjia-bkoff/src/main/webapp/apiUser/add.ftl index 2f3071de2..01b6b9d82 100644 --- a/projects/fangjia-bkoff/src/main/webapp/apiUser/add.ftl +++ b/projects/fangjia-bkoff/src/main/webapp/apiUser/add.ftl @@ -34,12 +34,12 @@
昵称 - + 用户� - + 密� @@ -59,7 +59,7 @@ 账户用途 �监控 - 监控 + �监控 + 监控 + + + + 是�需�API统计� + + �需� + 需� + + + + 是�需�API费用使用� + + �需� + 需� + + + + 是��醒�将到期 + + ��醒 + �醒 Email - + +
+ +
+
+ (�行一个,第一个为��,其余抄�)
+ 例�:
+ 123456@qq.com
+ 88888@163.com
+ 987654@gmail.com +
+ 销售负责人 - + 公� - + 估价调整比率 @@ -92,13 +125,21 @@ siteName - + 到期时间 - + + 客户�系人 + + + + 客户�系人电� + + ip地� + +
+ (�行一个,第一个为��,其余抄�)
+ 例�:
+ 123456@qq.com
+ 88888@163.com
+ 987654@gmail.com +
+ 销售负责人 - + 公� - + 估价调整比率 @@ -117,8 +150,8 @@ @@ -128,7 +161,15 @@ 到期时间 - " onFocus="WdatePicker({dateFmt:'yyyy-MM-dd'})"/> + " onFocus="WdatePicker({dateFmt:'yyyy-MM-dd'})"/> + + + 客户�系人 + + + + 客户�系人电� + ip地� @@ -156,6 +197,42 @@ return false } } + // 检查其他字段是�为空 + var email = $.trim($("#email").val()); + var manager = $.trim($("#manager").val()); + var company = $.trim($("#company").val()); + var deadTime = $.trim($("#deadTime").val()); + var contact = $.trim($("#contact").val()); + var phone = $.trim($("#phone").val()); + if (email === '') { + alert("邮箱�能为空�"); + return false; + } + if (manager === '') { + alert("销售负责人�能为空�"); + return false; + } + if (company === '') { + alert("公��能为空�"); + return false; + } + if (deadTime === '') { + alert("到期时间�能为空�"); + return false; + } + if (contact === '') { + alert("客户�系人�能为空�"); + return false; + } + if (phone === '') { + alert("客户�系人电��能为空�"); + return false; + } + if (email === '') { + alert("邮箱�能为空�"); + return false; + } + $("#submitForm").attr("action", "update"); $("#submitForm").submit(); } diff --git a/projects/fangjia-bkoff/src/main/webapp/apiUser/list.ftl b/projects/fangjia-bkoff/src/main/webapp/apiUser/list.ftl index fb5a7a7e0..f38b9b079 100644 --- a/projects/fangjia-bkoff/src/main/webapp/apiUser/list.ftl +++ b/projects/fangjia-bkoff/src/main/webapp/apiUser/list.ftl @@ -47,6 +47,35 @@
共有用户${apiUserBoList?size}个
+ +
+
+ + +
+
+ + +
+
+ + +
+ +
+
@@ -177,5 +206,23 @@ + \ No newline at end of file diff --git a/projects/fangjia-bkoff/src/main/webapp/developmentZone/edit.ftl b/projects/fangjia-bkoff/src/main/webapp/developmentZone/edit.ftl index b64ba3bac..87f03a8be 100644 --- a/projects/fangjia-bkoff/src/main/webapp/developmentZone/edit.ftl +++ b/projects/fangjia-bkoff/src/main/webapp/developmentZone/edit.ftl @@ -1,320 +1,344 @@ <#ftl attributes={"content_type":"text/html; charset=UTF-8"}> <#compress> - - - - - 开�区围�列表 - - - - -<#include "/common_js.ftl" /> -<#include "/layout/header.ftl" /> -
-
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +<#-- s--> + + + + + + + + + + + + + + + + + + +
+ + + +
+ + + + +
+ + + +
+ + + +
+ + + +
+ + + +
+ + + +
+ + +
+
+ + + +
+ + + +
+ + + +
+ + +
+
+ + +
+
+ + + +
+ + +
+
+ + + +
+ +
+ + + + + - + + + - - - - - - - - - - - - // 更新表�中的多边形点�置数� - function updatePolygonPoints() { - var polygons = map.getOverlays(BMap.Polygon); - for (var i = 0; i < polygons.length; i++) { - // 确�当�对象是一个多边形对象 - if (polygons[i] instanceof BMap.Polygon) { - var points = polygons[i].getPath(); - var bdShape = []; - for (var j = 0; j < points.length; j++) { - var location = []; - location.push(points[j].lng); - location.push(points[j].lat); - bdShape.push(location); - } - // 将更新�的点�置数�更新到表�中 - $("#bdShape").val(bdShape.join(";")); - } - } - } - - - fetchProvinces() - - - - - + + diff --git a/projects/fangjia-bkoff/src/main/webapp/developmentZone/editFence.ftl b/projects/fangjia-bkoff/src/main/webapp/developmentZone/editFence.ftl new file mode 100644 index 000000000..a18ce590d --- /dev/null +++ b/projects/fangjia-bkoff/src/main/webapp/developmentZone/editFence.ftl @@ -0,0 +1,535 @@ +<#ftl attributes={"content_type":"text/html; charset=UTF-8"}> +<#compress> + + + + + 开�区围�列表 + + + + + + + + + + <#include "/common_js.ftl" /> +
+
+
+
+ <#if developmentZone??> + + +
+ + <#-- --> +
+    +    + + +
+ 点1: + 点1�纬度: +
+ 点2: + 点2�纬度: +
+
+
+
+ <@d_city defaultValue="上海" callback="changeCity" callbackField="display" name="cityDisplay" showCountry = "1" /> +
+ + + + +
+
+ +
+
+
+ + + + + + + + + + + + + + + + + diff --git a/projects/fangjia-bkoff/src/main/webapp/developmentZone/list.ftl b/projects/fangjia-bkoff/src/main/webapp/developmentZone/list.ftl index 84c9bed96..cc13a219b 100644 --- a/projects/fangjia-bkoff/src/main/webapp/developmentZone/list.ftl +++ b/projects/fangjia-bkoff/src/main/webapp/developmentZone/list.ftl @@ -21,12 +21,21 @@ + + + + @@ -43,6 +52,7 @@ 城市 区域 区� + �作结果 是�有围� �作人员 修改日期 @@ -50,7 +60,7 @@ <#list developmentZoneList as it> - ${it.name!} + ${it.name!} <#if it.alias??> <#list it.alias as item> @@ -65,16 +75,25 @@ ${it.cityName1!} ${it.district!} ${it.block!} + ${it.operateResult!} <#if it.bdShape?has_content> 已有围� ${it.operator!} - ${it.createTime!?string("yyyy-MM-dd HH:mm:ss")} + + <#if it.createTime??> + ${it.createTime!?string("yyyy-MM-dd HH:mm:ss")} + <#else> + + + + 查看 - 新建围� + + 新建围� <#-- 删除--> diff --git a/projects/fangjia-bkoff/src/main/webapp/developmentZone/show.ftl b/projects/fangjia-bkoff/src/main/webapp/developmentZone/show.ftl index 817b5106d..03674eac3 100644 --- a/projects/fangjia-bkoff/src/main/webapp/developmentZone/show.ftl +++ b/projects/fangjia-bkoff/src/main/webapp/developmentZone/show.ftl @@ -20,7 +20,10 @@
<#if developmentZone??> - + <#if developmentZone??> + + + @@ -47,6 +50,10 @@ + + + + + +
�称 ${developmentZone.name!}
�积
别� @@ -61,13 +68,19 @@ 区� ${developmentZone.block!}
+
+ + <#-- --> +
开�区图片 -
+
-
@@ -92,12 +105,56 @@ new BMap.Point(${latlng[0]?string("#.######")}, ${latlng[1]?string("#.######")})<#if latlng_index lt developmentZone.bdShape.coordinates?size>, ], {strokeColor: "blue", strokeWeight: 2, strokeOpacity: 0.5}); - - - map.centerAndZoom(polygon.getBounds().getCenter(), 13); map.addOverlay(polygon); //增加多边形 + // 处�coords的格� + var coords = [ + <#list developmentZone.bdShape.coordinates as latlng> + { + lat: ${latlng[1]?string("#.######")}, + lng: ${latlng[0]?string("#.######")} + }<#if latlng_index lt developmentZone.bdShape.coordinates?size>, + + ]; + function haversine(lat1, lon1, lat2, lon2) { + const R = 6371; // 地��径(公里) + const lat1Rad = lat1 * (Math.PI / 180); + const lat2Rad = lat2 * (Math.PI / 180); + const deltaLat = (lat2 - lat1) * (Math.PI / 180); + const deltaLon = (lon2 - lon1) * (Math.PI / 180); + + const a = Math.sin(deltaLat / 2) ** 2 + + Math.cos(lat1Rad) * Math.cos(lat2Rad) * + Math.sin(deltaLon / 2) ** 2; + + const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); + return R * c; // 返回�离(公里) + } + + function calculateArea(coords) { + let area = 0; + const n = coords.length; + + for (let i = 0; i < n; i++) { + const j = (i + 1) % n; + area += coords[i].lng * coords[j].lat; + area -= coords[j].lng * coords[i].lat; + } + area = Math.abs(area) / 2; // 平方度 + + // 转�为平方公里 + const conversionFactor = 111.32; // 大约�度�纬度的公里数(考虑到地�的曲率) + return area * conversionFactor * conversionFactor; // 返回�积(平方公里) + } + + const areaInDegrees = calculateArea(coords); + // const areaInSquareKilometers = areaInDegrees * 123.5; // 转�为平方公里 + const areaInSquareKilometers = areaInDegrees; // 转�为平方公里 + document.getElementById('areaInSquareKilometers').value = areaInSquareKilometers.toFixed(2); + document.getElementById('areaDisplay').innerText = areaInSquareKilometers.toFixed(2) + ' 平方公里'; + + diff --git a/projects/fangjia-bkoff/src/main/webapp/district/add.ftl b/projects/fangjia-bkoff/src/main/webapp/district/add.ftl index 49795b1c1..8623963f8 100644 --- a/projects/fangjia-bkoff/src/main/webapp/district/add.ftl +++ b/projects/fangjia-bkoff/src/main/webapp/district/add.ftl @@ -643,7 +643,7 @@ - + <#----> - + + - + <#----> + + <#include "../jsconstants.ftl" /> + + + + + <#include "/header/v6/_header.ftl"/> +
+
+ <#if pager.totalRows gt 0> +
+ <@d_pager action="hidelist" currentPage=pager.currentPage controller="district" totalPages=pager.totalPages theme="topSearch" anchor="pagelist"/> +
+ + + +
+ <#if pager.totalRows gt pager.pageSize> +
+ <@d_pager action="hidelist" currentPage=pager.currentPage controller="district" totalPages=pager.totalPages anchor="pagelist"/> +
+ +
+ +
+ +
+ + + + + \ No newline at end of file diff --git a/projects/fangjia-coresite/src/main/webapp/district/seoInfo.ftl b/projects/fangjia-coresite/src/main/webapp/district/seoInfo.ftl new file mode 100644 index 000000000..076a12008 --- /dev/null +++ b/projects/fangjia-coresite/src/main/webapp/district/seoInfo.ftl @@ -0,0 +1,111 @@ + +<#compress> + + + + <#include "../jsconstants.ftl" /> + + + + + + + + + + + + + + + + +<#include "/header/v6/_header.ftl"/> + + +
+
+
+
+
+

+

${city!} ${region!} ${districtAddress!}

+
+
+
  • å°�区å�‡ä»·
  • 56565å…ƒ/㎡
+
  • 环比
  • 3.6
+
  • å�Œæ¯”
  • 12.3
+
+
+ + <#include "../houseReport/district_price.ftl"/> + + + <#include "../houseReport/district_around_map2.ftl"/> +
+
+
+<#include "/header/v6/_footer.ftl"/> + + + +<#----> +<#----> + + + + + + + + + + + + \ No newline at end of file diff --git a/projects/fangjia-coresite/src/main/webapp/evaluation/reportNew.ftl b/projects/fangjia-coresite/src/main/webapp/evaluation/reportNew.ftl index 4be5992ee..34a2e10c4 100644 --- a/projects/fangjia-coresite/src/main/webapp/evaluation/reportNew.ftl +++ b/projects/fangjia-coresite/src/main/webapp/evaluation/reportNew.ftl @@ -3,7 +3,7 @@ ${cityName}房产在线评估 - 房价网 fangjia.com - + <#include "../jsconstants.ftl" /> @@ -36,6 +36,7 @@ .adBoxLoan{width:100%;height:auto;background:none;border:solid 1px #f3f3f3;} .swiper-container{margin:0 1rem;margin-top:2rem;padding-bottom:1.5rem;top:0;} .swiper-container-horizontal > .swiper-pagination{bottom:0;} + .evaluation_content1 .error {top: 380px;} } @media (min-width:450px) and (max-width:600px) { .evaluation_inputInfo .cityChoice,.evaluation_inputInfo > div > div span{width:82%;} @@ -72,18 +73,18 @@ <#include "/header/v6/_header.ftl"/> <#include "/evaluation/checkUserNewRedirct.ftl"/> -
-
-
-
-

- -
-
-
-
+<#--
--> +<#--
--> +<#--
--> +<#--
--> +<#--

--> +<#--
--> +<#--
申请试用
--> +<#--
--> +<#--
--> +<#--
--> +<#--
--> +<#--
-->
diff --git a/projects/fangjia-coresite/src/main/webapp/header/v6/_header.ftl b/projects/fangjia-coresite/src/main/webapp/header/v6/_header.ftl index 280861ade..2b45d159d 100644 --- a/projects/fangjia-coresite/src/main/webapp/header/v6/_header.ftl +++ b/projects/fangjia-coresite/src/main/webapp/header/v6/_header.ftl @@ -80,11 +80,11 @@
  • - 房产大数æ�® + 在线估值
      -
    • 全国房价查询
    • -
    • 在线房产估值
    • +
    • 房价查询
    • +
    • 房产估值
    • <#--
    • æ•°æ�®èƒ½åŠ›
    • --> <#--
    • 法æ‹�房
    • --> <#--
    • 咨询研究
    • --> diff --git a/projects/fangjia-coresite/src/main/webapp/houseReport/district_around_map2.ftl b/projects/fangjia-coresite/src/main/webapp/houseReport/district_around_map2.ftl new file mode 100644 index 000000000..4b1b758da --- /dev/null +++ b/projects/fangjia-coresite/src/main/webapp/houseReport/district_around_map2.ftl @@ -0,0 +1,128 @@ + + + + + +
      +
      �区周边�套 +<#-- --> +
      +
      +
      +
      +
      +
      +
      + + + + + + + \ No newline at end of file diff --git a/projects/fangjia-coresite/src/main/webapp/index.ftl b/projects/fangjia-coresite/src/main/webapp/index.ftl index 0cbd06b3f..356dea3ad 100644 --- a/projects/fangjia-coresite/src/main/webapp/index.ftl +++ b/projects/fangjia-coresite/src/main/webapp/index.ftl @@ -3,7 +3,8 @@ - + +<#-- --> 选择房价网-为金�机构解决地�标准化难题_治�率高达90% - 房价网 fangjia.com @@ -47,14 +48,7 @@ <#--
    --> <#--
  • --> -<<<<<<< HEAD -<#--fixedNav01--> -======= -<#----> ->>>>>>> c7c2bae298951f01848f2b654c4c5e7fdba454c0 +
    @@ -971,7 +965,7 @@
    - + <#include "/header/v6/_footer.ftl"/> diff --git a/projects/fangjia-coresite/src/main/webapp/industry/bank.ftl b/projects/fangjia-coresite/src/main/webapp/industry/bank.ftl index 858f366db..676b36ebb 100644 --- a/projects/fangjia-coresite/src/main/webapp/industry/bank.ftl +++ b/projects/fangjia-coresite/src/main/webapp/industry/bank.ftl @@ -4,7 +4,7 @@ 银行洞察客户�网点布局�业务�销_选房价网 - 房价网 fangjia.com - + <#include "../jsconstants.ftl" /> diff --git a/projects/fangjia-coresite/src/main/webapp/jsconstants.ftl b/projects/fangjia-coresite/src/main/webapp/jsconstants.ftl index bf723dca2..5363a5992 100644 --- a/projects/fangjia-coresite/src/main/webapp/jsconstants.ftl +++ b/projects/fangjia-coresite/src/main/webapp/jsconstants.ftl @@ -21,4 +21,5 @@ var Constants = { + <#include "baidu_analysis.ftl" /> diff --git a/projects/fangjia-coresite/src/main/webapp/solution/dishu.ftl b/projects/fangjia-coresite/src/main/webapp/solution/dishu.ftl index 09dba1751..6712055e6 100644 --- a/projects/fangjia-coresite/src/main/webapp/solution/dishu.ftl +++ b/projects/fangjia-coresite/src/main/webapp/solution/dishu.ftl @@ -72,7 +72,7 @@
    结�业务定制 解决方案
    -
    赋能�通场景与业务,个性化定制行业解决方案,为�业地�应用场景助力
    +
    赋能��场景与业务,个性化定制行业解决方案,为�业地�应用场景助力
    diff --git a/projects/fangjia-coresite/src/main/webapp/trend/trend.ftl b/projects/fangjia-coresite/src/main/webapp/trend/trend.ftl index 375d1ec56..8a7c2935c 100644 --- a/projects/fangjia-coresite/src/main/webapp/trend/trend.ftl +++ b/projects/fangjia-coresite/src/main/webapp/trend/trend.ftl @@ -18,8 +18,8 @@ <#assign _currentCityDisplay>${cityName} - <#assign PAGE_TITLE>${affectValue}房价走势 - 房价网 fangjia.com - <#assign PAGE_KEYWORDS>${affectValue}房价走势,${affectValue}房产数�,${affectValue}房价 + <#assign PAGE_TITLE>${affectValue}房价走势 - ${cityName}房产网 fangjia.com + <#assign PAGE_KEYWORDS>${affectValue}房价走势,${affectValue}房产数�,${affectValue}房价,二手房�价查询,楼盘估值,在线评估 <#assign headDesc>房价网�供${affectValue}�时���的房价走势图,�费查询最新季度房价�最近�年房价走势�去年�期房价走势�以�${affectValue}房价历�走势等信�。 <#assign PAGE_DESCRIPTION>${headDesc} @@ -52,18 +52,18 @@
    ${affectValue}
    -
    -
    -
    -
    -

    - -
    -
    -
    -
    +<#--
    --> +<#--
    --> +<#--
    --> +<#--
    --> +<#--

    --> +<#--
    --> +<#--
    申请试用
    --> +<#--
    --> +<#--
    --> +<#--
    --> +<#--
    --> +<#--
    -->
    @@ -80,7 +80,7 @@

    房价网自2006年起累计在线估值次数

    -

      æ¬¡

    +

      æ¬¡

    房产数�覆盖全国367个城市地区�80万楼盘�8000万房�库�70万楼盘字段�5000万POI数�。

    @@ -362,7 +362,7 @@ let animateFrame; // 清除 requestAnimationFrame 请求动画帧 // 数字动画 function digitalAnimation() { - startNum += 6658; // 速度的计算�以为�数 。数字越大,滚动越快 + startNum += 68; // 速度的计算�以为�数 。数字越大,滚动越快 if(maxNum > 0){ if (startNum >= maxNum) { startNum = maxNum; @@ -389,10 +389,12 @@ timeout: 100000, success: function(model) { // $("#evalCount").text(toThousands(model.evalCount)); - var startNum = document.getElementById("evalCount").innerHTML; + // var startNum = document.getElementById("evalCount").innerHTML; + var startNum = toThousands(model.evalCount - 10000) if (startNum == ''){ $("#evalCount").text(toThousands(model.evalCount)); }else{ + $("#evalCount").text(startNum); numScroll(startNum,model.evalCount); } }, @@ -406,10 +408,10 @@ const month = now.getMonth() + 1; // 月 let divElement = document.getElementById("date"); - divElement.innerHTML = ""+year+"年"+month+"月"+""; + $("#date").html(""+year+"年"+month+"月"+"") let divElement2 = document.getElementById("date2"); - divElement2.innerHTML = ""+year+"年"+month+"月"+""; + $("#date2").html(""+year+"年"+month+"月"+"") $(function(){ $('.td04').each(function(i){ diff --git a/projects/fangjia-coresite/src/main/webapp/user/login.ftl b/projects/fangjia-coresite/src/main/webapp/user/login.ftl index ec4a9dc8b..254c8002f 100644 --- a/projects/fangjia-coresite/src/main/webapp/user/login.ftl +++ b/projects/fangjia-coresite/src/main/webapp/user/login.ftl @@ -28,7 +28,7 @@ .main{width:768px;padding-top:0;} .main_left{width:768px;height: 650px;} .main_left div{padding-top: 140px;margin-left:30px;} - .main_left div p{text-align: left;} + .main_left div p{text-align: left; margin-top: 20px;} .main_left div p label{font-size: 42px;letter-spacing: 0px;} .main_left div p span{font-size: 30px;} .main_left div p small{display: none;} @@ -38,10 +38,10 @@ @media(max-device-width:414px){ .main_left{background:url(${staticUrl}/images/fangjia/v6/login-1.jpg);background-size: 100% 100%;background-repeat: no-repeat;background-position: center;} .main{width:414px;} - .main_left{width:414px;height: 450px;} + .main_left{width:414px;height: 200px;} .main_right{width:414px;height: 560px;} .main_left div {margin-left: 10px;margin-right: 70px;padding-top: 20px;} - .main_left div p label{font-size: 42px;letter-spacing: 0px;} + .main_left div p label{font-size: 22px;letter-spacing: 0px;} .main_left div p span {font-size: 27px;} .user00{width: 350px;height: 400px;margin-top: 30px;} .inputInfo {margin-bottom: 20px;} @@ -74,6 +74,7 @@ } .error {top: -20px;left: 106px;} + .main_left div {margin-top: 50px;} diff --git a/projects/fangjia-coresite/src/main/webapp/user/regSuccess.ftl b/projects/fangjia-coresite/src/main/webapp/user/regSuccess.ftl index 5e5d02187..cd9b74e06 100644 --- a/projects/fangjia-coresite/src/main/webapp/user/regSuccess.ftl +++ b/projects/fangjia-coresite/src/main/webapp/user/regSuccess.ftl @@ -62,12 +62,12 @@ diff --git a/projects/fangjia-coresite/src/main/webapp/user/register.ftl b/projects/fangjia-coresite/src/main/webapp/user/register.ftl index 53127ca3a..6fce0e272 100644 --- a/projects/fangjia-coresite/src/main/webapp/user/register.ftl +++ b/projects/fangjia-coresite/src/main/webapp/user/register.ftl @@ -12,11 +12,11 @@ - + @@ -69,7 +99,7 @@
      -
    • 欢迎注册房价网
    • +
    • 欢迎注册房价网
    @@ -99,7 +129,7 @@
    - +
    两次密��一致
    @@ -110,11 +140,13 @@ 我已阅读并接�《用户�议》
    - -
    或
    - -

    若有任何问题,请致电客�:400-188-3787

    +
    + + +
    或
    + +

    若有任何问题,请致电客�:400-188-3787

    diff --git a/projects/fangjia-dal/src/main/java/com/fangjia/dal/SeawaterQuery.java b/projects/fangjia-dal/src/main/java/com/fangjia/dal/SeawaterQuery.java index 66cc39114..4eac9a928 100644 --- a/projects/fangjia-dal/src/main/java/com/fangjia/dal/SeawaterQuery.java +++ b/projects/fangjia-dal/src/main/java/com/fangjia/dal/SeawaterQuery.java @@ -32,6 +32,12 @@ public class SeawaterQuery { private Pager pager; private String editEstateType; + private Double lat; + + private Double lng; + + private Integer radius; + public String getId() { return id; } @@ -239,4 +245,28 @@ public class SeawaterQuery { public void setEditEstateType(String editEstateType) { this.editEstateType = editEstateType; } + + public Double getLat() { + return lat; + } + + public void setLat(Double lat) { + this.lat = lat; + } + + public Double getLng() { + return lng; + } + + public void setLng(Double lng) { + this.lng = lng; + } + + public Integer getRadius() { + return radius; + } + + public void setRadius(Integer radius) { + this.radius = radius; + } } diff --git a/projects/fangjia-dal/src/main/java/com/fangjia/dal/datastore/model/RentHouse.java b/projects/fangjia-dal/src/main/java/com/fangjia/dal/datastore/model/RentHouse.java index da86e9653..63a13c075 100644 --- a/projects/fangjia-dal/src/main/java/com/fangjia/dal/datastore/model/RentHouse.java +++ b/projects/fangjia-dal/src/main/java/com/fangjia/dal/datastore/model/RentHouse.java @@ -38,6 +38,8 @@ public class RentHouse extends BaseHouse implements DatastoreEntity { private String block; private Integer totalPrice; private Integer totalPriceRange; + + private Integer avgPrice; /** * ³ö×âÀàÐÍ */ @@ -760,4 +762,14 @@ public class RentHouse extends BaseHouse implements DatastoreEntity { this.houseRequire = houseRequire; } + @Transient + @Column(name = "avg_price") + public Integer getAvgPrice() { + return avgPrice; + } + + public void setAvgPrice(Integer avgPrice) { + this.avgPrice = avgPrice; + } + } diff --git a/projects/fangjia-dal/src/main/java/com/fangjia/dal/mongo/dao/ApiCountLogDao.java b/projects/fangjia-dal/src/main/java/com/fangjia/dal/mongo/dao/ApiCountLogDao.java new file mode 100644 index 000000000..d60612775 --- /dev/null +++ b/projects/fangjia-dal/src/main/java/com/fangjia/dal/mongo/dao/ApiCountLogDao.java @@ -0,0 +1,9 @@ +package com.fangjia.dal.mongo.dao; + +import com.fangjia.dal.MongoDao; +import com.fangjia.dal.mongo.model.ApiCountLog; +import com.fangjia.dal.mongo.model.DevelopmentZone; + +public interface ApiCountLogDao extends MongoDao { + +} diff --git a/projects/fangjia-dal/src/main/java/com/fangjia/dal/mongo/dao/ApiCountLogDaoImpl.java b/projects/fangjia-dal/src/main/java/com/fangjia/dal/mongo/dao/ApiCountLogDaoImpl.java new file mode 100644 index 000000000..4bfa0ebc0 --- /dev/null +++ b/projects/fangjia-dal/src/main/java/com/fangjia/dal/mongo/dao/ApiCountLogDaoImpl.java @@ -0,0 +1,9 @@ +package com.fangjia.dal.mongo.dao; + +import com.fangjia.dal.MongoDaoImpl; +import com.fangjia.dal.mongo.model.ApiCountLog; +import com.fangjia.dal.mongo.model.DevelopmentZone; + +public class ApiCountLogDaoImpl extends MongoDaoImpl implements ApiCountLogDao { + +} diff --git a/projects/fangjia-dal/src/main/java/com/fangjia/dal/mongo/dao/PropertyStatsIndexDao.java b/projects/fangjia-dal/src/main/java/com/fangjia/dal/mongo/dao/PropertyStatsIndexDao.java new file mode 100644 index 000000000..c52e73f1e --- /dev/null +++ b/projects/fangjia-dal/src/main/java/com/fangjia/dal/mongo/dao/PropertyStatsIndexDao.java @@ -0,0 +1,9 @@ +package com.fangjia.dal.mongo.dao; + +import com.fangjia.dal.MongoDao; +import com.fangjia.dal.mongo.model.PropertyStatsIndex; +import com.fangjia.dal.mongo.model.StatsIndex; + +public interface PropertyStatsIndexDao extends MongoDao { + +} diff --git a/projects/fangjia-dal/src/main/java/com/fangjia/dal/mongo/dao/PropertyStatsIndexDaoImpl.java b/projects/fangjia-dal/src/main/java/com/fangjia/dal/mongo/dao/PropertyStatsIndexDaoImpl.java new file mode 100644 index 000000000..6c8e5f7b8 --- /dev/null +++ b/projects/fangjia-dal/src/main/java/com/fangjia/dal/mongo/dao/PropertyStatsIndexDaoImpl.java @@ -0,0 +1,10 @@ +package com.fangjia.dal.mongo.dao; + +import com.fangjia.dal.MongoDaoImpl; +import com.fangjia.dal.mongo.model.PropertyStatsIndex; +import com.fangjia.dal.mongo.model.StatsIndex; + + +public class PropertyStatsIndexDaoImpl extends MongoDaoImpl implements PropertyStatsIndexDao { + +} diff --git a/projects/fangjia-dal/src/main/java/com/fangjia/dal/mongo/dao/SeaweedImagesDao.java b/projects/fangjia-dal/src/main/java/com/fangjia/dal/mongo/dao/SeaweedImagesDao.java new file mode 100644 index 000000000..f4b8ba4b2 --- /dev/null +++ b/projects/fangjia-dal/src/main/java/com/fangjia/dal/mongo/dao/SeaweedImagesDao.java @@ -0,0 +1,9 @@ +package com.fangjia.dal.mongo.dao; + +import com.fangjia.dal.MongoDao; +import com.fangjia.dal.mongo.model.DevelopmentZone; +import com.fangjia.dal.mongo.model.SeaweedImages; + +public interface SeaweedImagesDao extends MongoDao { + +} diff --git a/projects/fangjia-dal/src/main/java/com/fangjia/dal/mongo/dao/SeaweedImagesDaoImpl.java b/projects/fangjia-dal/src/main/java/com/fangjia/dal/mongo/dao/SeaweedImagesDaoImpl.java new file mode 100644 index 000000000..898d882c0 --- /dev/null +++ b/projects/fangjia-dal/src/main/java/com/fangjia/dal/mongo/dao/SeaweedImagesDaoImpl.java @@ -0,0 +1,7 @@ +package com.fangjia.dal.mongo.dao; + +import com.fangjia.dal.MongoDaoImpl; +import com.fangjia.dal.mongo.model.SeaweedImages; + +public class SeaweedImagesDaoImpl extends MongoDaoImpl implements SeaweedImagesDao{ +} diff --git a/projects/fangjia-dal/src/main/java/com/fangjia/dal/mongo/model/ApiCountLog.java b/projects/fangjia-dal/src/main/java/com/fangjia/dal/mongo/model/ApiCountLog.java new file mode 100644 index 000000000..00b512da9 --- /dev/null +++ b/projects/fangjia-dal/src/main/java/com/fangjia/dal/mongo/model/ApiCountLog.java @@ -0,0 +1,127 @@ +package com.fangjia.dal.mongo.model; + +import com.fangjia.dal.MongoEntity; + +import javax.persistence.*; +import java.util.Date; +import java.util.List; +import java.util.Map; + + +@Entity +@Table(name = "business.api_count_log") +public class ApiCountLog implements MongoEntity { + + private String id; + + private Long userId; + + private String userName; + + private String uri; + + private String uriName; + + private String operate; + + private String operator; + + private Date operateTime; + + // Ð޸ĴÎÊýǰ×Ü´ÎÊý + private Integer oldCount; + // Ð޸ĴÎÊýºóµÄ´ÎÊý + private Integer newCount; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "_id") + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + @Column(name = "user_id") + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + @Column(name = "uri") + public String getUri() { + return uri; + } + + public void setUri(String uri) { + this.uri = uri; + } + + @Column(name = "uri_name") + public String getUriName() { + return uriName; + } + + public void setUriName(String uriName) { + this.uriName = uriName; + } + + @Column(name = "operate") + public String getOperate() { + return operate; + } + + public void setOperate(String operate) { + this.operate = operate; + } + + @Column(name = "operator") + public String getOperator() { + return operator; + } + + public void setOperator(String operator) { + this.operator = operator; + } + + @Column(name = "operate_time") + public Date getOperateTime() { + return operateTime; + } + + public void setOperateTime(Date operateTime) { + this.operateTime = operateTime; + } + + @Column(name = "old_count") + public Integer getOldCount() { + return oldCount; + } + + public void setOldCount(Integer oldCount) { + this.oldCount = oldCount; + } + + @Column(name = "new_count") + public Integer getNewCount() { + return newCount; + } + + public void setNewCount(Integer newCount) { + this.newCount = newCount; + } + + @Column(name = "user_name") + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } +} diff --git a/projects/fangjia-dal/src/main/java/com/fangjia/dal/mongo/model/DevelopmentZone.java b/projects/fangjia-dal/src/main/java/com/fangjia/dal/mongo/model/DevelopmentZone.java index f0e2bcd88..b548c6c0f 100644 --- a/projects/fangjia-dal/src/main/java/com/fangjia/dal/mongo/model/DevelopmentZone.java +++ b/projects/fangjia-dal/src/main/java/com/fangjia/dal/mongo/model/DevelopmentZone.java @@ -38,6 +38,10 @@ public class DevelopmentZone implements MongoEntity { //Ôö¼Ó±ðÃû×Ö¶Î private List alias; + private String imgUrl; + + private String operateResult; + @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "_id") @@ -216,4 +220,22 @@ public class DevelopmentZone implements MongoEntity { public void setAlias(List alias) { this.alias = alias; } + + @Column(name = "img_url") + public String getImgUrl() { + return imgUrl; + } + + public void setImgUrl(String imgUrl) { + this.imgUrl = imgUrl; + } + + @Column(name = "operate_result") + public String getOperateResult() { + return operateResult; + } + + public void setOperateResult(String operateResult) { + this.operateResult = operateResult; + } } diff --git a/projects/fangjia-dal/src/main/java/com/fangjia/dal/mongo/model/PropertyStatsIndex.java b/projects/fangjia-dal/src/main/java/com/fangjia/dal/mongo/model/PropertyStatsIndex.java new file mode 100644 index 000000000..923e94247 --- /dev/null +++ b/projects/fangjia-dal/src/main/java/com/fangjia/dal/mongo/model/PropertyStatsIndex.java @@ -0,0 +1,282 @@ +package com.fangjia.dal.mongo.model; + +import com.fangjia.dal.MongoEntity; + +import javax.persistence.*; +import java.util.Date; + +/** + * ¼Û¸ñÖ¸Êý + */ +@Entity +@Table(name = "fangjia_stat.property_stats_index") +public class PropertyStatsIndex implements MongoEntity{ + /** + * + */ + private static final long serialVersionUID = -9102764355476337768L; + + private String id; + + private String city; + + private String district; + + private String name; + + private Integer yearmonth; + + private Integer source; + + private String remark; + + private Double chain; + + private Double yeartoyear; + + private Double fixedbase; + + private Double belowChain; + + private Double belowYeartoyear; + + private Double belowFixedbase; + + private Double amongChain; + + private Double amongYeartoyear; + + private Double amongFixedbase; + + private Double aboveChain; + + private Double aboveYeartoyear; + + private Double aboveFixedbase; + + private Date cDate; + + private String cat; + + private Double fangIndex; + + private Double fangChain; + + private String type; + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "_id") + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + @Column(name = "city") + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + @Column(name = "district") + public String getDistrict() { + return district; + } + + public void setDistrict(String district) { + this.district = district; + } + + @Column(name = "name") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Column(name = "c_date") + public Date getcDate() { + return cDate; + } + + public void setcDate(Date cDate) { + this.cDate = cDate; + } + + @Column(name = "yearmonth") + public Integer getYearmonth() { + return yearmonth; + } + + public void setYearmonth(Integer yearmonth) { + this.yearmonth = yearmonth; + } + + @Column(name = "source") + public Integer getSource() { + return source; + } + + public void setSource(Integer source) { + this.source = source; + } + + @Column(name = "remark") + public String getRemark() { + return remark; + } + + public void setRemark(String remark) { + this.remark = remark; + } + @Column(name = "below_chain") + public Double getBelowChain() { + return belowChain; + } + + public void setBelowChain(Double belowChain) { + this.belowChain = belowChain; + } + + @Column(name = "below_yeartoyear") + public Double getBelowYeartoyear() { + return belowYeartoyear; + } + + public void setBelowYeartoyear(Double belowYeartoyear) { + this.belowYeartoyear = belowYeartoyear; + } + + @Column(name = "below_fixedbase") + public Double getBelowFixedbase() { + return belowFixedbase; + } + + public void setBelowFixedbase(Double belowFixedbase) { + this.belowFixedbase = belowFixedbase; + } + + @Column(name = "among_chain") + public Double getAmongChain() { + return amongChain; + } + + public void setAmongChain(Double amongChain) { + this.amongChain = amongChain; + } + + @Column(name = "among_yeartoyear") + public Double getAmongYeartoyear() { + return amongYeartoyear; + } + + public void setAmongYeartoyear(Double amongYeartoyear) { + this.amongYeartoyear = amongYeartoyear; + } + + @Column(name = "among_fixedbase") + public Double getAmongFixedbase() { + return amongFixedbase; + } + + public void setAmongFixedbase(Double amongFixedbase) { + this.amongFixedbase = amongFixedbase; + } + + @Column(name = "above_chain") + public Double getAboveChain() { + return aboveChain; + } + + public void setAboveChain(Double aboveChain) { + this.aboveChain = aboveChain; + } + + @Column(name = "above_yeartoyear") + public Double getAboveYeartoyear() { + return aboveYeartoyear; + } + + public void setAboveYeartoyear(Double aboveYeartoyear) { + this.aboveYeartoyear = aboveYeartoyear; + } + + @Column(name = "above_fixedbase") + public Double getAboveFixedbase() { + return aboveFixedbase; + } + + public void setAboveFixedbase(Double aboveFixedbase) { + this.aboveFixedbase = aboveFixedbase; + } + + @Column(name = "cat") + public String getCat() { + return cat; + } + + public void setCat(String cat) { + this.cat = cat; + } + + @Column(name = "fang_index") + public Double getFangIndex() { + return fangIndex; + } + + public void setFangIndex(Double fangIndex) { + this.fangIndex = fangIndex; + } + + @Column(name = "fang_chain") + public Double getFangChain() { + return fangChain; + } + + public void setFangChain(Double fangChain) { + this.fangChain = fangChain; + } + + @Column(name = "chain") + public Double getChain() { + return chain; + } + + public void setChain(Double chain) { + this.chain = chain; + } + + @Column(name = "yeartoyear") + public Double getYeartoyear() { + return yeartoyear; + } + + public void setYeartoyear(Double yeartoyear) { + this.yeartoyear = yeartoyear; + } + + @Column(name = "fixedbase") + public Double getFixedbase() { + return fixedbase; + } + + public void setFixedbase(Double fixedbase) { + this.fixedbase = fixedbase; + } + + @Column(name = "type") + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } +} diff --git a/projects/fangjia-dal/src/main/java/com/fangjia/dal/mongo/model/SeaweedImages.java b/projects/fangjia-dal/src/main/java/com/fangjia/dal/mongo/model/SeaweedImages.java new file mode 100644 index 000000000..33d6b6dee --- /dev/null +++ b/projects/fangjia-dal/src/main/java/com/fangjia/dal/mongo/model/SeaweedImages.java @@ -0,0 +1,90 @@ +package com.fangjia.dal.mongo.model; + +import com.fangjia.dal.MongoEntity; + +import javax.persistence.*; +import java.util.Date; +import java.util.List; +import java.util.Map; + +@Entity +@Table(name = "fangjia_base.seaweed_images") +public class SeaweedImages implements MongoEntity { + + private static final long serialVersionUID = 4356189537384834754L; + private String id; + private String city; + private String district; + + private Map> floorplanPics; + + private Date mDate; + private String name; + private List outPics; + + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "_id") + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + + @Column(name = "city") + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + @Column(name = "district") + public String getDistrict() { + return district; + } + + public void setDistrict(String district) { + this.district = district; + } + @Column(name = "floorplan_pics") + public Map> getFloorplanPics() { + return floorplanPics; + } + + public void setFloorplanPics(Map> floorplanPics) { + this.floorplanPics = floorplanPics; + } + + @Column(name = "m_date") + public Date getmDate() { + return mDate; + } + + public void setmDate(Date mDate) { + this.mDate = mDate; + } + + @Column(name = "name") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Column(name = "out_pics") + public List getOutPics() { + return outPics; + } + + public void setOutPics(List outPics) { + this.outPics = outPics; + } +} diff --git a/projects/fangjia-dal/src/main/java/com/fangjia/dal/mongo/model/StatsIndex.java b/projects/fangjia-dal/src/main/java/com/fangjia/dal/mongo/model/StatsIndex.java index c0565b537..d117a1bf6 100644 --- a/projects/fangjia-dal/src/main/java/com/fangjia/dal/mongo/model/StatsIndex.java +++ b/projects/fangjia-dal/src/main/java/com/fangjia/dal/mongo/model/StatsIndex.java @@ -14,7 +14,7 @@ import com.fangjia.dal.MongoEntity; * ¼Û¸ñÖ¸Êý */ @Entity -@Table(name = "fangjia.stats_index") +@Table(name = "fangjia_stat.stats_index") public class StatsIndex implements MongoEntity{ /** * @@ -24,19 +24,24 @@ public class StatsIndex implements MongoEntity{ private String id; private String city; + + private String district; - private String yearmonth; + private Integer yearmonth; private Integer source; private String remark; private Double newChain; - + private Double chain; + private Double newYeartoyear; - + private Double yeartoyear; + private Double newFixedbase; - + private Double fixedbase; + private Double belowChain; private Double belowYeartoyear; @@ -62,6 +67,8 @@ public class StatsIndex implements MongoEntity{ private Double fangIndex; private Double fangChain; + + private String type; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "_id") @@ -82,6 +89,14 @@ public class StatsIndex implements MongoEntity{ this.city = city; } + @Column(name = "district") + public String getDistrict() { + return district; + } + + public void setDistrict(String district) { + this.district = district; + } @Column(name = "c_date") public Date getcDate() { @@ -91,13 +106,13 @@ public class StatsIndex implements MongoEntity{ public void setcDate(Date cDate) { this.cDate = cDate; } - + @Column(name = "yearmonth") - public String getYearmonth() { + public Integer getYearmonth() { return yearmonth; } - public void setYearmonth(String yearmonth) { + public void setYearmonth(Integer yearmonth) { this.yearmonth = yearmonth; } @@ -118,34 +133,6 @@ public class StatsIndex implements MongoEntity{ public void setRemark(String remark) { this.remark = remark; } - - @Column(name = "new_chain") - public Double getNewChain() { - return newChain; - } - - public void setNewChain(Double newChain) { - this.newChain = newChain; - } - - @Column(name = "new_yeartoyear") - public Double getNewYeartoyear() { - return newYeartoyear; - } - - public void setNewYeartoyear(Double newYeartoyear) { - this.newYeartoyear = newYeartoyear; - } - - @Column(name = "new_fixedbase") - public Double getNewFixedbase() { - return newFixedbase; - } - - public void setNewFixedbase(Double newFixedbase) { - this.newFixedbase = newFixedbase; - } - @Column(name = "below_chain") public Double getBelowChain() { return belowChain; @@ -253,6 +240,67 @@ public class StatsIndex implements MongoEntity{ public void setFangChain(Double fangChain) { this.fangChain = fangChain; } - - + + @Column(name = "chain") + public Double getChain() { + return chain; + } + + public void setChain(Double chain) { + this.chain = chain; + } + + @Column(name = "yeartoyear") + public Double getYeartoyear() { + return yeartoyear; + } + + public void setYeartoyear(Double yeartoyear) { + this.yeartoyear = yeartoyear; + } + + @Column(name = "fixedbase") + public Double getFixedbase() { + return fixedbase; + } + + public void setFixedbase(Double fixedbase) { + this.fixedbase = fixedbase; + } + + @Column(name = "type") + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + @Column(name = "new_chain") + public Double getNewChain() { + return newChain; + } + + public void setNewChain(Double newChain) { + this.newChain = newChain; + } + + @Column(name = "new_yeartoyear") + public Double getNewYeartoyear() { + return newYeartoyear; + } + + public void setNewYeartoyear(Double newYeartoyear) { + this.newYeartoyear = newYeartoyear; + } + + @Column(name = "new_fixedbase") + public Double getNewFixedbase() { + return newFixedbase; + } + + public void setNewFixedbase(Double newFixedbase) { + this.newFixedbase = newFixedbase; + } } diff --git a/projects/fangjia-dal/src/main/java/com/fangjia/dal/mongo/open/model/OpenResource.java b/projects/fangjia-dal/src/main/java/com/fangjia/dal/mongo/open/model/OpenResource.java index fff320ac5..e0f519223 100644 --- a/projects/fangjia-dal/src/main/java/com/fangjia/dal/mongo/open/model/OpenResource.java +++ b/projects/fangjia-dal/src/main/java/com/fangjia/dal/mongo/open/model/OpenResource.java @@ -36,6 +36,10 @@ public class OpenResource implements MongoEntity { private Boolean saveResult; + private int pubStatus; + + private int apiCode; + @Id @GeneratedValue @Column(name = "_id") @@ -115,4 +119,22 @@ public class OpenResource implements MongoEntity { public void setSaveResult(Boolean saveResult) { this.saveResult = saveResult; } + + @Column(name = "pub_status") + public int getPubStatus() { + return pubStatus; + } + + public void setPubStatus(int pubStatus) { + this.pubStatus = pubStatus; + } + + @Column(name = "api_code") + public int getApiCode() { + return apiCode; + } + + public void setApiCode(int apiCode) { + this.apiCode = apiCode; + } } diff --git a/projects/fangjia-dal/src/main/java/com/fangjia/dal/seawater/dao/SeawaterDaoImpl.java b/projects/fangjia-dal/src/main/java/com/fangjia/dal/seawater/dao/SeawaterDaoImpl.java index ab018c2ac..39a29c099 100644 --- a/projects/fangjia-dal/src/main/java/com/fangjia/dal/seawater/dao/SeawaterDaoImpl.java +++ b/projects/fangjia-dal/src/main/java/com/fangjia/dal/seawater/dao/SeawaterDaoImpl.java @@ -15,507 +15,522 @@ import net.sf.json.JSONObject; import org.sothis.core.util.Pager; public class SeawaterDaoImpl extends com.fangjia.dal.SeawaterDaoImpl implements SeawaterDao { - - - private static final String ES_USER = "developer"; - private static final String ES_PASSWORD = "5e8edd851d2fdfbd7415232c67367cc3"; - - - @Override - public long findSeawatersCountFromEs(String category, String city, String region, String name, List alias, - List regionAlias, Integer startDate, Integer endDate, Integer room, String root,String table) { - int count = queryCount(null,category,city,region,name,alias,regionAlias,startDate,endDate,room,root,null,false,-1,-1,table); - return count; - } - - @Override - public Seawater findByIdFromEs(String id,String table) { - Seawater seawater = null; - SeawaterQuery query = new SeawaterQuery(); - query.setId(id); - query.setTable(table); - Pager pager = new Pager(); - pager.setStartRow(-1); - pager.setPageSize(-1); - query.setPager(pager); - List jsonList = queryList(query); - if(jsonList == null){ - return null; - }else{ - List seawaterList = wrapSeawater(jsonList); - if(seawaterList.size() > 0){ - seawater = seawaterList.get(0); - } - } - return seawater; - } - - @Override - public List findSeawatersFromEs(String category, String city, String region, String name, List alias, List regionAlias, Integer startDate, Integer endDate, Double startArea, Double endArea, Integer startPrice, Integer endPrice, Integer room, String root, String sort, boolean order, int start, int limit, String table) { - List seawaterList= new ArrayList(); - SeawaterQuery query = new SeawaterQuery(); - query.setCat(category); - query.setCityDisplay(city); - query.setRegion(region); - query.setDistrictName(name); - query.setDistrictAlias(alias); - query.setRegionAlias(regionAlias); - query.setStartDate(startDate); - query.setEndDate(endDate); - query.setStartArea(startArea); - query.setEndArea(endArea); - query.setStartPrice(startPrice); - query.setEndPrice(endPrice); - query.setRoom(room); - query.setRootName(root); - query.setOrder(order); - Pager pager = new Pager(); - pager.setStartRow(start); - pager.setPageSize(limit); - query.setPager(pager); - query.setTable(table); - List jsonList = queryList(query); - if(jsonList == null){ - return null; - }else{ - seawaterList = wrapSeawater(jsonList); - } - return seawaterList; - } - - @Override - public List findSeawatersByQuery(SeawaterQuery query){ - List seawaterList; - List jsonList = queryList(query); - if(jsonList == null){ - return null; - }else{ - seawaterList = wrapSeawater(jsonList); - } - return seawaterList; - } - - @Override - public long findSeawatersCountByQuery(SeawaterQuery query) { - int count = queryCount(query); - return count; - } - - @Override - public List findHouses(String city, String region, List alias, Integer minPrice, Integer maxPrice, Integer limit) { - JSONObject reqBody = new JSONObject(); - reqBody.put("from", 0); - reqBody.put("size", limit); - JSONObject query = new JSONObject(); - JSONObject bool = new JSONObject(); - JSONArray must = new JSONArray(); - must.add(addMatch("city", city)); - must.add(addMatch("region", region)); - must.add(addTerms("district_name", alias)); - must.add(addMatch("cat", "sell")); - must.add(addRange("avg_price", minPrice, maxPrice)); - must.add(addRangeGte("p_date", 20210501)); - - bool.put("must", must); - query.put("bool", bool); - reqBody.put("query", query); - Base64 token = new Base64(); - String authenticationEncoding = token.encodeAsString(new String(""+ES_USER+":"+ES_PASSWORD+"").getBytes()); - HttpRequest request = new HttpRequest(); - Map headers = new HashMap(); - headers.put("Content-Type", "application/json"); - headers.put("Authorization", "Basic "+authenticationEncoding+""); - try { - String response = request.postWithBody("http://es.fangjia.com:9200/latest_seawater/_search", reqBody, headers, "UTF-8"); - JSONObject json = JSONObject.fromObject(response); - if(!json.containsKey("hits") || !json.getJSONObject("hits").containsKey("hits")){ - return Collections.emptyList(); - } - JSONArray hits = json.getJSONObject("hits").getJSONArray("hits"); - List results = new ArrayList(); - for(int i=0 ;i < hits.size(); i++){ - JSONObject jsonObject = hits.getJSONObject(i); - results.add(jsonObject); - } - return wrapSeawater(results); - - } catch (HttpRequestException e) { - e.printStackTrace(); - } - return new ArrayList(); - } - - @Override - public void deleteById(String id) { - deleteByIds(Arrays.asList(id)); - } - - private Map buildHeader() { - Base64 token = new Base64(); - String authenticationEncoding = token.encodeAsString(new String("" + ES_USER + ":" + ES_PASSWORD + "").getBytes()); - Map headers = new HashMap(); - headers.put("Content-Type", "application/json"); - headers.put("Authorization", "Basic " + authenticationEncoding + ""); - return headers; - } - - @Override - public void deleteByIds(List idList) { - HttpRequest request = new HttpRequest(); - - JSONObject reqBody = new JSONObject(); - JSONObject query = new JSONObject(); - JSONObject bool = new JSONObject(); - JSONArray must = new JSONArray(); - must.add(addTerms("_id", idList)); - bool.put("must", must); - query.put("bool", bool); - reqBody.put("query", query); - - JSONObject script = new JSONObject(); - script.put("source", "ctx._source.status=1"); - reqBody.put("script", script); - - try { - request.postWithBody("http://es.fangjia.com:9200/seawater/_update_by_query", reqBody, this.buildHeader(), "UTF-8"); - } catch (HttpRequestException e) { - e.printStackTrace(); - } - } - - @Override - public void batchDeleteByParams(SeawaterQuery query) { - HttpRequest request = new HttpRequest(); - - JSONObject reqBody = wrapQueryParams(query); - - JSONObject script = new JSONObject(); - script.put("source", "ctx._source.status=1"); - script.put("lang", "painless"); - reqBody.put("script", script); - - try { - request.postWithBody("http://es.fangjia.com:9200/seawater/_update_by_query?conflicts=proceed&wait_for_completion=false", reqBody, this.buildHeader(), "UTF-8"); - } catch (HttpRequestException e) { - e.printStackTrace(); - } - } - - @Override - public void batchUpdateEstateType(SeawaterQuery query) { - HttpRequest request = new HttpRequest(); - - JSONObject reqBody = wrapQueryParams(query); - - JSONObject script = new JSONObject(); - script.put("source", "ctx._source.estate_type="+"'"+query.getEditEstateType()+"'"); - script.put("lang", "painless"); - reqBody.put("script", script); - - try { - request.postWithBody("http://es.fangjia.com:9200/seawater/_update_by_query?conflicts=proceed&wait_for_completion=false", reqBody, this.buildHeader(), "UTF-8"); - } catch (HttpRequestException e) { - e.printStackTrace(); - } - } - - private JSONObject addMatch(String name, String value){ - JSONObject term = new JSONObject(); - JSONObject match = new JSONObject(); - match.put(name, value); - term.put("match", match); - return term; - } - - private JSONObject addTerms(String name, List value){ - JSONObject terms = new JSONObject(); - JSONObject match = new JSONObject(); - match.put(name, value); - terms.put("terms", match); - return terms; - } - - private JSONObject addRange(String name, Number min, Number max){ - JSONObject term = new JSONObject(); - JSONObject range = new JSONObject(); - JSONObject rangeValue = new JSONObject(); - rangeValue.put("gt", min); - rangeValue.put("lt", max); - range.put(name, rangeValue); - term.put("range", range); - return term; - } - - private JSONObject addRangeGte(String name, Number min){ - JSONObject term = new JSONObject(); - JSONObject range = new JSONObject(); - JSONObject rangeValue = new JSONObject(); - rangeValue.put("gte", min); - range.put(name, rangeValue); - term.put("range", range); - return term; - } - private List wrapSeawater(List jsonList){ - List seawaterList= new ArrayList(); - for(int i=0 ;i < jsonList.size(); i++){ - Seawater seawater = new Seawater(); - seawater.setId(jsonList.get(i).getString("_id")); - JSONObject source = jsonList.get(i).getJSONObject("_source"); - seawater.setCategory(source.getString("cat")); - seawater.setCity(source.getString("city")); - seawater.setRegion(source.getString("region")); - seawater.setDistrictName(source.getString("district_name")); - if(source.containsKey("address")){ - seawater.setAddress(source.getString("address")); - } - if(source.containsKey("name")){ - seawater.setName(source.getString("name")); - } - if(source.containsKey("direction")){ - seawater.setDirection(source.getString("direction")); - } - if(source.containsKey("block")){ - seawater.setBlock(source.getString("block")); - } - try{ - seawater.setTotalPrice(source.getInt("total_price")); - }catch(NumberFormatException e){ - seawater.setTotalPrice(0); - } - try{ - seawater.setArea(source.getDouble("area")); - }catch(NumberFormatException e){ - seawater.setArea(0d); - } - try{ - seawater.setHeight(source.getInt("height")); - }catch(Exception e){ - seawater.setHeight(0); - } - try{ - seawater.setFloor(source.getInt("floor")); - }catch(Exception e){ - seawater.setFloor(0); - } - try{ - seawater.setFloorInfo(source.getString("floor_info")); - }catch(Exception e){ + private static final String ES_USER = "developer"; + private static final String ES_PASSWORD = "5e8edd851d2fdfbd7415232c67367cc3"; - } - if(source.containsKey("fitment")){ - seawater.setFitment(source.getString("fitment")); - } - try{ - seawater.setRoom(source.getInt("room")); - }catch(Exception e){ - seawater.setRoom(0); - } - try{ - seawater.setHall(source.getInt("hall")); - }catch(Exception e){ - seawater.setHall(0); - } - try{ - seawater.setToilet(source.getInt("toilet")); - }catch(Exception e){ - seawater.setToilet(0); - } - try{ - seawater.setpDate(source.getInt("p_date")); - }catch(Exception e){ - seawater.setpDate(0); - } - if(source.containsKey("url")){ - seawater.setUrl(source.getString("url")); - } - if(source.containsKey("avg_price")){ - seawater.setAvgPrice(source.getInt("avg_price")); - } - if(source.containsKey("root")){ - seawater.setRoot(source.getString("root")); - } - if(source.containsKey("estate_type")){ - seawater.setEstateType(source.getString("estate_type")); - } + @Override + public long findSeawatersCountFromEs(String category, String city, String region, String name, List alias, + List regionAlias, Integer startDate, Integer endDate, Integer room, String root, String table) { + int count = queryCount(null, category, city, region, name, alias, regionAlias, startDate, endDate, room, root, null, false, -1, -1, table); + return count; + } - if(source.containsKey("build_type")){ - seawater.setBuildType(source.getString("build_type")); - } - if(source.containsKey("status")){ - seawater.setStatus(source.getInt("status")); - } - - if(source.containsKey("lift")){ - seawater.setLift(source.getInt("lift")); - } - - if(source.containsKey("lift_household")){ - seawater.setLiftHousehold(source.getInt("lift_household")); - } - - if(source.containsKey("room_structure")){ - seawater.setRoomStructure(source.getString("room_structure")); - } - - if(source.containsKey("trade_property")){ - seawater.setTradeProperty(source.getString("trade_property")); - } - if(source.containsKey("property_ownership")){ - seawater.setPropertyOwnership(source.getString("property_ownership")); - } - if(source.containsKey("housing_age")){ - seawater.setHousingAge(source.getString("housing_age")); - } - if(source.containsKey("elevator")){ - seawater.setElevator(source.getString("elevator")); - } - seawaterList.add(seawater); + @Override + public Seawater findByIdFromEs(String id, String table) { + Seawater seawater = null; + SeawaterQuery query = new SeawaterQuery(); + query.setId(id); + query.setTable(table); + Pager pager = new Pager(); + pager.setStartRow(-1); + pager.setPageSize(-1); + query.setPager(pager); + List jsonList = queryList(query); + if (jsonList == null) { + return null; + } else { + List seawaterList = wrapSeawater(jsonList); + if (seawaterList.size() > 0) { + seawater = seawaterList.get(0); + } } - return seawaterList; - } - - private JSONObject query(String id,String category, String city, String region, String name, List alias, - List regionAlias, Integer startDate, Integer endDate, Double startArea, Double endArea, Integer startPrice, Integer endPrice, - Integer room, String root,String sort, boolean order, int start, int limit,String table){ - long time1 = System.currentTimeMillis(); - JSONObject reqBody = new JSONObject(); + return seawater; + } + + @Override + public List findSeawatersFromEs(String category, String city, String region, String name, List alias, List regionAlias, Integer startDate, Integer endDate, Double startArea, Double endArea, Integer startPrice, Integer endPrice, Integer room, String root, String sort, boolean order, int start, int limit, String table) { + List seawaterList = new ArrayList(); + SeawaterQuery query = new SeawaterQuery(); + query.setCat(category); + query.setCityDisplay(city); + query.setRegion(region); + query.setDistrictName(name); + query.setDistrictAlias(alias); + query.setRegionAlias(regionAlias); + query.setStartDate(startDate); + query.setEndDate(endDate); + query.setStartArea(startArea); + query.setEndArea(endArea); + query.setStartPrice(startPrice); + query.setEndPrice(endPrice); + query.setRoom(room); + query.setRootName(root); + query.setOrder(order); + Pager pager = new Pager(); + pager.setStartRow(start); + pager.setPageSize(limit); + query.setPager(pager); + query.setTable(table); + List jsonList = queryList(query); + if (jsonList == null) { + return null; + } else { + seawaterList = wrapSeawater(jsonList); + } + return seawaterList; + } + + @Override + public List findSeawatersByQuery(SeawaterQuery query) { + List seawaterList; + List jsonList = queryList(query); + if (jsonList == null) { + return null; + } else { + seawaterList = wrapSeawater(jsonList); + } + return seawaterList; + } + + @Override + public long findSeawatersCountByQuery(SeawaterQuery query) { + int count = queryCount(query); + return count; + } + + @Override + public List findHouses(String city, String region, List alias, Integer minPrice, Integer maxPrice, Integer limit) { + JSONObject reqBody = new JSONObject(); + reqBody.put("from", 0); + reqBody.put("size", limit); + JSONObject query = new JSONObject(); + JSONObject bool = new JSONObject(); + JSONArray must = new JSONArray(); + must.add(addMatch("city", city)); + must.add(addMatch("region", region)); + must.add(addTerms("district_name", alias)); + must.add(addMatch("cat", "sell")); + must.add(addRange("avg_price", minPrice, maxPrice)); + must.add(addRangeGte("p_date", 20210501)); + + bool.put("must", must); + query.put("bool", bool); + reqBody.put("query", query); + Base64 token = new Base64(); + String authenticationEncoding = token.encodeAsString(new String("" + ES_USER + ":" + ES_PASSWORD + "").getBytes()); + HttpRequest request = new HttpRequest(); + Map headers = new HashMap(); + headers.put("Content-Type", "application/json"); + headers.put("Authorization", "Basic " + authenticationEncoding + ""); + try { + String response = request.postWithBody("http://es.fangjia.com:9200/latest_seawater/_search", reqBody, headers, "UTF-8"); + JSONObject json = JSONObject.fromObject(response); + if (!json.containsKey("hits") || !json.getJSONObject("hits").containsKey("hits")) { + return Collections.emptyList(); + } + JSONArray hits = json.getJSONObject("hits").getJSONArray("hits"); + List results = new ArrayList(); + for (int i = 0; i < hits.size(); i++) { + JSONObject jsonObject = hits.getJSONObject(i); + results.add(jsonObject); + } + return wrapSeawater(results); + + } catch (HttpRequestException e) { + e.printStackTrace(); + } + return new ArrayList(); + } + + @Override + public void deleteById(String id) { + deleteByIds(Arrays.asList(id)); + } + + private Map buildHeader() { + Base64 token = new Base64(); + String authenticationEncoding = token.encodeAsString(new String("" + ES_USER + ":" + ES_PASSWORD + "").getBytes()); + Map headers = new HashMap(); + headers.put("Content-Type", "application/json"); + headers.put("Authorization", "Basic " + authenticationEncoding + ""); + return headers; + } + + @Override + public void deleteByIds(List idList) { + HttpRequest request = new HttpRequest(); + + JSONObject reqBody = new JSONObject(); + JSONObject query = new JSONObject(); + JSONObject bool = new JSONObject(); + JSONArray must = new JSONArray(); + must.add(addTerms("_id", idList)); + bool.put("must", must); + query.put("bool", bool); + reqBody.put("query", query); + + JSONObject script = new JSONObject(); + script.put("source", "ctx._source.status=1"); + reqBody.put("script", script); + + try { + request.postWithBody("http://es.fangjia.com:9200/seawater/_update_by_query", reqBody, this.buildHeader(), "UTF-8"); + } catch (HttpRequestException e) { + e.printStackTrace(); + } + } + + @Override + public void batchDeleteByParams(SeawaterQuery query) { + HttpRequest request = new HttpRequest(); + + JSONObject reqBody = wrapQueryParams(query); + + JSONObject script = new JSONObject(); + script.put("source", "ctx._source.status=1"); + script.put("lang", "painless"); + reqBody.put("script", script); + + try { + request.postWithBody("http://es.fangjia.com:9200/seawater/_update_by_query?conflicts=proceed&wait_for_completion=false", reqBody, this.buildHeader(), "UTF-8"); + } catch (HttpRequestException e) { + e.printStackTrace(); + } + } + + @Override + public void batchUpdateEstateType(SeawaterQuery query) { + HttpRequest request = new HttpRequest(); + + JSONObject reqBody = wrapQueryParams(query); + + JSONObject script = new JSONObject(); + script.put("source", "ctx._source.estate_type=" + "'" + query.getEditEstateType() + "'"); + script.put("lang", "painless"); + reqBody.put("script", script); + + try { + request.postWithBody("http://es.fangjia.com:9200/seawater/_update_by_query?conflicts=proceed&wait_for_completion=false", reqBody, this.buildHeader(), "UTF-8"); + } catch (HttpRequestException e) { + e.printStackTrace(); + } + } + + private JSONObject addMatch(String name, String value) { + JSONObject term = new JSONObject(); + JSONObject match = new JSONObject(); + match.put(name, value); + term.put("match", match); + return term; + } + + private JSONObject addTerms(String name, List value) { + JSONObject terms = new JSONObject(); + JSONObject match = new JSONObject(); + match.put(name, value); + terms.put("terms", match); + return terms; + } + + private JSONObject addRange(String name, Number min, Number max) { + JSONObject term = new JSONObject(); + JSONObject range = new JSONObject(); + JSONObject rangeValue = new JSONObject(); + rangeValue.put("gt", min); + rangeValue.put("lt", max); + range.put(name, rangeValue); + term.put("range", range); + return term; + } + + private JSONObject addRangeGte(String name, Number min) { + JSONObject term = new JSONObject(); + JSONObject range = new JSONObject(); + JSONObject rangeValue = new JSONObject(); + rangeValue.put("gte", min); + range.put(name, rangeValue); + term.put("range", range); + return term; + } + + + private List wrapSeawater(List jsonList) { + List seawaterList = new ArrayList(); + for (int i = 0; i < jsonList.size(); i++) { + Seawater seawater = new Seawater(); + seawater.setId(jsonList.get(i).getString("_id")); + JSONObject source = jsonList.get(i).getJSONObject("_source"); + seawater.setCategory(source.getString("cat")); + seawater.setCity(source.getString("city")); + seawater.setRegion(source.getString("region")); + seawater.setDistrictName(source.getString("district_name")); + if (source.containsKey("location")) { + String location = source.getJSONObject("location").getString("lon") + "," + source.getJSONObject("location").getString("lat"); + seawater.setLocation(location); + } + if (source.containsKey("address")) { + seawater.setAddress(source.getString("address")); + } + if (source.containsKey("name")) { + seawater.setName(source.getString("name")); + } + if (source.containsKey("direction")) { + seawater.setDirection(source.getString("direction")); + } + if (source.containsKey("block")) { + seawater.setBlock(source.getString("block")); + } + try { + seawater.setTotalPrice(source.getInt("total_price")); + } catch (NumberFormatException e) { + seawater.setTotalPrice(0); + } + try { + seawater.setArea(source.getDouble("area")); + } catch (NumberFormatException e) { + seawater.setArea(0d); + } + try { + seawater.setHeight(source.getInt("height")); + } catch (Exception e) { + seawater.setHeight(0); + } + try { + seawater.setFloor(source.getInt("floor")); + } catch (Exception e) { + seawater.setFloor(0); + } + try { + seawater.setFloorInfo(source.getString("floor_info")); + } catch (Exception e) { + + } + if (source.containsKey("fitment")) { + seawater.setFitment(source.getString("fitment")); + } + try { + seawater.setRoom(source.getInt("room")); + } catch (Exception e) { + seawater.setRoom(0); + } + try { + seawater.setHall(source.getInt("hall")); + } catch (Exception e) { + seawater.setHall(0); + } + try { + seawater.setToilet(source.getInt("toilet")); + } catch (Exception e) { + seawater.setToilet(0); + } + try { + seawater.setpDate(source.getInt("p_date")); + } catch (Exception e) { + seawater.setpDate(0); + } + if (source.containsKey("url")) { + seawater.setUrl(source.getString("url")); + } + if (source.containsKey("avg_price")) { + seawater.setAvgPrice(source.getInt("avg_price")); + } + if (source.containsKey("root")) { + seawater.setRoot(source.getString("root")); + } + + if (source.containsKey("estate_type")) { + seawater.setEstateType(source.getString("estate_type")); + } + + if (source.containsKey("build_type")) { + seawater.setBuildType(source.getString("build_type")); + } + if (source.containsKey("status")) { + seawater.setStatus(source.getInt("status")); + } + + if (source.containsKey("lift")) { + seawater.setLift(source.getInt("lift")); + } + + if (source.containsKey("lift_household")) { + seawater.setLiftHousehold(source.getInt("lift_household")); + } + + if (source.containsKey("room_structure")) { + seawater.setRoomStructure(source.getString("room_structure")); + } + + if (source.containsKey("trade_property")) { + seawater.setTradeProperty(source.getString("trade_property")); + } + if (source.containsKey("property_ownership")) { + seawater.setPropertyOwnership(source.getString("property_ownership")); + } + if (source.containsKey("housing_age")) { + seawater.setHousingAge(source.getString("housing_age")); + } + if (source.containsKey("elevator")) { + seawater.setElevator(source.getString("elevator")); + } + if (source.containsKey("level")) { + seawater.setLevel(source.getString("level")); + } + if (source.containsKey("business_range")) { + seawater.setBusinessRange(source.getString("business_range")); + } + try { + seawater.setDistance((int) jsonList.get(i).getJSONArray("sort").getDouble(0)); + } catch (Exception e) { + seawater.setDistance(null); + } + seawaterList.add(seawater); + } + return seawaterList; + } + + private JSONObject query(String id, String category, String city, String region, String name, List alias, + List regionAlias, Integer startDate, Integer endDate, Double startArea, Double endArea, Integer startPrice, Integer endPrice, + Integer room, String root, String sort, boolean order, int start, int limit, String table) { + long time1 = System.currentTimeMillis(); + JSONObject reqBody = new JSONObject(); JSONObject q = new JSONObject(); JSONObject query = new JSONObject(); List jsonList = new ArrayList(); - if(StringUtils.isNotBlank(id)) { - JSONObject param = new JSONObject(); - param.put("_id", id); - JSONObject temp = new JSONObject(); - temp.put("term", param); - jsonList.add(temp); - } - if(StringUtils.isNotBlank(category)) { - JSONObject param = new JSONObject(); - param.put("cat", category); - JSONObject temp = new JSONObject(); - temp.put("term", param); - jsonList.add(temp); - } - + if (StringUtils.isNotBlank(id)) { + JSONObject param = new JSONObject(); + param.put("_id", id); + JSONObject temp = new JSONObject(); + temp.put("term", param); + jsonList.add(temp); + } + if (StringUtils.isNotBlank(category)) { + JSONObject param = new JSONObject(); + param.put("cat", category); + JSONObject temp = new JSONObject(); + temp.put("term", param); + jsonList.add(temp); + } + Set namesList = new LinkedHashSet(); - if(StringUtils.isNotBlank(name)) { - namesList.add(name); - } - if (alias != null) { - namesList.addAll(alias); - } - if(namesList != null && namesList.size() > 0){ - JSONObject param = new JSONObject(); - param.put("district_name", namesList); - JSONObject temp = new JSONObject(); - temp.put("terms", param); - jsonList.add(temp); - } - - Set regionsList = new LinkedHashSet(); - if(StringUtils.isNotBlank(region)) { - regionsList.add(region); - } - if (regionAlias != null) { - regionsList.addAll(regionAlias); - } - if(regionsList != null && regionsList.size() > 0){ - JSONObject param = new JSONObject(); - param.put("region", regionsList); - JSONObject temp = new JSONObject(); - temp.put("terms", param); - jsonList.add(temp); - } - - if(StringUtils.isNotBlank(city)){ - JSONObject param = new JSONObject(); - param.put("city", city); - JSONObject temp = new JSONObject(); - temp.put("term", param); - jsonList.add(temp); - } - if(room != null) { - JSONObject param = new JSONObject(); - param.put("room", room); - JSONObject temp = new JSONObject(); - temp.put("term", param); - jsonList.add(temp); - } - if(StringUtils.isNotBlank(root)) { - JSONObject param = new JSONObject(); - param.put("root", root); - JSONObject temp = new JSONObject(); - temp.put("term", param); - jsonList.add(temp); - } - - if(startDate != null || endDate != null){ - JSONObject param = new JSONObject(); - JSONObject temp = new JSONObject(); - JSONObject temp2 = new JSONObject(); - if(startDate != null){ - temp2.put("gte", startDate); - } - if(endDate != null){ - temp2.put("lte", endDate); - } - param.put("p_date", temp2); - temp.put("range", param); - jsonList.add(temp); - } + if (StringUtils.isNotBlank(name)) { + namesList.add(name); + } + if (alias != null) { + namesList.addAll(alias); + } + if (namesList != null && namesList.size() > 0) { + JSONObject param = new JSONObject(); + param.put("district_name", namesList); + JSONObject temp = new JSONObject(); + temp.put("terms", param); + jsonList.add(temp); + } + + Set regionsList = new LinkedHashSet(); + if (StringUtils.isNotBlank(region)) { + regionsList.add(region); + } + if (regionAlias != null) { + regionsList.addAll(regionAlias); + } + if (regionsList != null && regionsList.size() > 0) { + JSONObject param = new JSONObject(); + param.put("region", regionsList); + JSONObject temp = new JSONObject(); + temp.put("terms", param); + jsonList.add(temp); + } + + if (StringUtils.isNotBlank(city)) { + JSONObject param = new JSONObject(); + param.put("city", city); + JSONObject temp = new JSONObject(); + temp.put("term", param); + jsonList.add(temp); + } + if (room != null) { + JSONObject param = new JSONObject(); + param.put("room", room); + JSONObject temp = new JSONObject(); + temp.put("term", param); + jsonList.add(temp); + } + if (StringUtils.isNotBlank(root)) { + JSONObject param = new JSONObject(); + param.put("root", root); + JSONObject temp = new JSONObject(); + temp.put("term", param); + jsonList.add(temp); + } + + if (startDate != null || endDate != null) { + JSONObject param = new JSONObject(); + JSONObject temp = new JSONObject(); + JSONObject temp2 = new JSONObject(); + if (startDate != null) { + temp2.put("gte", startDate); + } + if (endDate != null) { + temp2.put("lte", endDate); + } + param.put("p_date", temp2); + temp.put("range", param); + jsonList.add(temp); + } - if(startArea != null || endArea != null){ - JSONObject param = new JSONObject(); - JSONObject temp = new JSONObject(); - JSONObject temp2 = new JSONObject(); - if(startArea != null){ - temp2.put("gte", startArea); - } - if(endArea != null){ - temp2.put("lte", endArea); - } - param.put("area", temp2); - temp.put("range", param); - jsonList.add(temp); - } + if (startArea != null || endArea != null) { + JSONObject param = new JSONObject(); + JSONObject temp = new JSONObject(); + JSONObject temp2 = new JSONObject(); + if (startArea != null) { + temp2.put("gte", startArea); + } + if (endArea != null) { + temp2.put("lte", endArea); + } + param.put("area", temp2); + temp.put("range", param); + jsonList.add(temp); + } - if(startPrice != null || endPrice != null){ - JSONObject param = new JSONObject(); - JSONObject temp = new JSONObject(); - JSONObject temp2 = new JSONObject(); - if(startPrice != null){ - temp2.put("gte", startPrice); - } - if(endPrice != null){ - temp2.put("lte", endPrice); - } - param.put("avg_price", temp2); - temp.put("range", param); - jsonList.add(temp); - } - - if(StringUtils.isNotBlank(sort)){ - JSONObject jsonOrder = new JSONObject(); - if(order){ - jsonOrder.put("order", "asc"); - }else{ - jsonOrder.put("order", "desc"); - } - JSONObject jsonSort = new JSONObject(); - jsonSort.put(sort, jsonOrder); - List sortJsonList = new ArrayList(); - sortJsonList.add(jsonSort); - reqBody.put("sort", sortJsonList); - } - - if(start >= 0){ + if (startPrice != null || endPrice != null) { + JSONObject param = new JSONObject(); + JSONObject temp = new JSONObject(); + JSONObject temp2 = new JSONObject(); + if (startPrice != null) { + temp2.put("gte", startPrice); + } + if (endPrice != null) { + temp2.put("lte", endPrice); + } + param.put("avg_price", temp2); + temp.put("range", param); + jsonList.add(temp); + } + + if (StringUtils.isNotBlank(sort)) { + JSONObject jsonOrder = new JSONObject(); + if (order) { + jsonOrder.put("order", "asc"); + } else { + jsonOrder.put("order", "desc"); + } + JSONObject jsonSort = new JSONObject(); + jsonSort.put(sort, jsonOrder); + List sortJsonList = new ArrayList(); + sortJsonList.add(jsonSort); + reqBody.put("sort", sortJsonList); + } + + if (start >= 0) { reqBody.put("from", start); } - if(limit >= 0){ + if (limit >= 0) { reqBody.put("size", limit); } @@ -529,201 +544,241 @@ public class SeawaterDaoImpl extends com.fangjia.dal.SeawaterDaoImpl i query.put("must", jsonList); q.put("bool", query); reqBody.put("query", q); - //Óû§Ãû:ÃÜÂë + //Óû§Ãû:ÃÜÂë Base64 token = new Base64(); - String authenticationEncoding = token.encodeAsString(new String(""+ES_USER+":"+ES_PASSWORD+"").getBytes()); + String authenticationEncoding = token.encodeAsString(new String("" + ES_USER + ":" + ES_PASSWORD + "").getBytes()); HttpRequest request = new HttpRequest(); Map headers = new HashMap(); headers.put("Content-Type", "application/json"); - headers.put("Authorization", "Basic "+authenticationEncoding+""); + headers.put("Authorization", "Basic " + authenticationEncoding + ""); try { - String response = request.postWithBody("http://es.fangjia.com:9200/"+table+"/_search?rest_total_hits_as_int=true", reqBody, headers, "UTF-8"); + String response = request.postWithBody("http://es.fangjia.com:9200/" + table + "/_search?rest_total_hits_as_int=true", reqBody, headers, "UTF-8"); JSONObject json = JSONObject.fromObject(response); long time2 = System.currentTimeMillis(); - System.out.println(time2-time1); + System.out.println(time2 - time1); return json; } catch (HttpRequestException e) { e.printStackTrace(); } return null; - } + } - private JSONObject query(SeawaterQuery query){ - long time1 = System.currentTimeMillis(); - JSONObject reqBody = new JSONObject(); - JSONObject q = new JSONObject(); - JSONObject queryJson = new JSONObject(); - List jsonList = new ArrayList(); - if(StringUtils.isNotBlank(query.getId())) { - JSONObject param = new JSONObject(); - param.put("_id", query.getId()); - JSONObject temp = new JSONObject(); - temp.put("term", param); - jsonList.add(temp); - } - if(StringUtils.isNotBlank(query.getCat())) { - JSONObject param = new JSONObject(); - param.put("cat", query.getCat()); - JSONObject temp = new JSONObject(); - temp.put("term", param); - jsonList.add(temp); - } + private JSONObject query(SeawaterQuery query) { + long time1 = System.currentTimeMillis(); + JSONObject reqBody = new JSONObject(); + JSONObject q = new JSONObject(); + JSONObject queryJson = new JSONObject(); + List jsonList = new ArrayList(); + Double lat = query.getLat(); + Double lng = query.getLng(); + Integer radius = query.getRadius(); + JSONObject filter = new JSONObject(); + // Ìí¼ÓµØÀíλÖùýÂËÆ÷ºÍÅÅÐò + if (lat != null && lng != null && radius != null) { + // 1. ÉèÖõØÀíλÖòÎÊý + JSONObject geoDistanceParam = new JSONObject(); + geoDistanceParam.put("lat", lat); + geoDistanceParam.put("lon", lng); - Set namesList = new LinkedHashSet(); - if(StringUtils.isNotBlank(query.getDistrictName())) { - namesList.add(query.getDistrictName()); - } - if (query.getDistrictAlias() != null) { - namesList.addAll(query.getDistrictAlias()); - } - if(namesList != null && namesList.size() > 0){ - JSONObject param = new JSONObject(); - param.put("district_name", namesList); - JSONObject temp = new JSONObject(); - temp.put("terms", param); - jsonList.add(temp); - } + // 2. ÉèÖà geo_distance ¹ýÂËÆ÷£¬ÏÞÖÆ½á¹ûÔÚÖ¸¶¨µÄ°ë¾¶·¶Î§ÄÚ - Set regionsList = new LinkedHashSet(); - if(StringUtils.isNotBlank(query.getRegion())) { - regionsList.add(query.getRegion()); - } - if (query.getRegionAlias() != null) { - regionsList.addAll(query.getRegionAlias()); - } - if(regionsList != null && regionsList.size() > 0){ - JSONObject param = new JSONObject(); - param.put("region", regionsList); - JSONObject temp = new JSONObject(); - temp.put("terms", param); - jsonList.add(temp); - } + JSONObject geoDistance = new JSONObject(); + geoDistance.put("distance", radius + "m"); // °ë¾¶ÉèÖÃΪ 3000km + geoDistance.put("location", geoDistanceParam); // ʹÓøø¶¨µÄ¾­Î³¶È + filter.put("geo_distance", geoDistance); - if(StringUtils.isNotBlank(query.getCityDisplay())){ - JSONObject param = new JSONObject(); - param.put("city", query.getCityDisplay()); - JSONObject temp = new JSONObject(); - temp.put("term", param); - jsonList.add(temp); - } - if(StringUtils.isNotBlank(query.getEstateType())) { - JSONObject param = new JSONObject(); - param.put("estate_type", query.getEstateType()); - JSONObject temp = new JSONObject(); - temp.put("term", param); - jsonList.add(temp); - } - if(query.getRoom() != null) { - JSONObject param = new JSONObject(); - param.put("room", query.getRoom()); - JSONObject temp = new JSONObject(); - temp.put("term", param); - jsonList.add(temp); - } - if(StringUtils.isNotBlank(query.getRootName())) { - JSONObject param = new JSONObject(); - param.put("root", query.getRootName()); - JSONObject temp = new JSONObject(); - temp.put("term", param); - jsonList.add(temp); - } + // 3. ¹¹½¨²éѯÌå +// filter.put("filter", geoDistanceFilter); +// jsonList.add(filter); +// reqBody.put("query", filter); + // 4. Ìí¼Ó°´¾àÀëÅÅÐòµÄ²¿·Ö + JSONObject geoDistanceSort = new JSONObject(); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("order", "asc"); + jsonObject.put("location", geoDistanceParam); + jsonObject.put("unit", "m"); + jsonObject.put("distance_type", "arc"); + geoDistanceSort.put("_geo_distance", jsonObject); + // 5. ½«ÅÅÐò²¿·ÖÌí¼Óµ½ÇëÇóÌå + List sortJsonList = new ArrayList(); + sortJsonList.add(geoDistanceSort); + reqBody.put("sort", sortJsonList); + } + if (StringUtils.isNotBlank(query.getId())) { + JSONObject param = new JSONObject(); + param.put("_id", query.getId()); + JSONObject temp = new JSONObject(); + temp.put("term", param); + jsonList.add(temp); + } + if (StringUtils.isNotBlank(query.getCat())) { + JSONObject param = new JSONObject(); + param.put("cat", query.getCat()); + JSONObject temp = new JSONObject(); + temp.put("term", param); + jsonList.add(temp); + } - if(query.getStartDate() != null || query.getEndDate() != null){ - JSONObject param = new JSONObject(); - JSONObject temp = new JSONObject(); - JSONObject temp2 = new JSONObject(); - if(query.getStartDate() != null){ - temp2.put("gte", query.getStartDate()); - } - if(query.getEndDate() != null){ - temp2.put("lte", query.getEndDate()); - } - param.put("p_date", temp2); - temp.put("range", param); - jsonList.add(temp); - } + Set namesList = new LinkedHashSet(); + if (StringUtils.isNotBlank(query.getDistrictName())) { + namesList.add(query.getDistrictName()); + } + if (query.getDistrictAlias() != null) { + namesList.addAll(query.getDistrictAlias()); + } + if (namesList != null && namesList.size() > 0) { + JSONObject param = new JSONObject(); + param.put("district_name", namesList); + JSONObject temp = new JSONObject(); + temp.put("terms", param); + jsonList.add(temp); + } + + Set regionsList = new LinkedHashSet(); + if (StringUtils.isNotBlank(query.getRegion())) { + regionsList.add(query.getRegion()); + } + if (query.getRegionAlias() != null) { + regionsList.addAll(query.getRegionAlias()); + } + if (regionsList != null && regionsList.size() > 0) { + JSONObject param = new JSONObject(); + param.put("region", regionsList); + JSONObject temp = new JSONObject(); + temp.put("terms", param); + jsonList.add(temp); + } + + if (StringUtils.isNotBlank(query.getCityDisplay())) { + JSONObject param = new JSONObject(); + param.put("city", query.getCityDisplay()); + JSONObject temp = new JSONObject(); + temp.put("term", param); + jsonList.add(temp); + } + if (StringUtils.isNotBlank(query.getEstateType())) { + JSONObject param = new JSONObject(); + param.put("estate_type", query.getEstateType()); + JSONObject temp = new JSONObject(); + temp.put("term", param); + jsonList.add(temp); + } + if (query.getRoom() != null) { + JSONObject param = new JSONObject(); + param.put("room", query.getRoom()); + JSONObject temp = new JSONObject(); + temp.put("term", param); + jsonList.add(temp); + } + if (StringUtils.isNotBlank(query.getRootName())) { + JSONObject param = new JSONObject(); + param.put("root", query.getRootName()); + JSONObject temp = new JSONObject(); + temp.put("term", param); + jsonList.add(temp); + } + + if (query.getStartDate() != null || query.getEndDate() != null) { + JSONObject param = new JSONObject(); + JSONObject temp = new JSONObject(); + JSONObject temp2 = new JSONObject(); + if (query.getStartDate() != null) { + temp2.put("gte", query.getStartDate()); + } + if (query.getEndDate() != null) { + temp2.put("lte", query.getEndDate()); + } + param.put("p_date", temp2); + temp.put("range", param); + jsonList.add(temp); + } - if(query.getStartArea() != null || query.getEndArea() != null){ - JSONObject param = new JSONObject(); - JSONObject temp = new JSONObject(); - JSONObject temp2 = new JSONObject(); - if(query.getStartArea() != null){ - temp2.put("gte", query.getStartArea()); - } - if(query.getEndArea() != null){ - temp2.put("lte", query.getEndArea()); - } - param.put("area", temp2); - temp.put("range", param); - jsonList.add(temp); - } + if (query.getStartArea() != null || query.getEndArea() != null) { + JSONObject param = new JSONObject(); + JSONObject temp = new JSONObject(); + JSONObject temp2 = new JSONObject(); + if (query.getStartArea() != null) { + temp2.put("gte", query.getStartArea()); + } + if (query.getEndArea() != null) { + temp2.put("lte", query.getEndArea()); + } + param.put("area", temp2); + temp.put("range", param); + jsonList.add(temp); + } - if(query.getStartPrice() != null || query.getEndPrice() != null){ - JSONObject param = new JSONObject(); - JSONObject temp = new JSONObject(); - JSONObject temp2 = new JSONObject(); - if(query.getStartPrice() != null){ - temp2.put("gte", query.getStartPrice()); - } - if(query.getEndPrice() != null){ - temp2.put("lte", query.getEndPrice()); - } - param.put("avg_price", temp2); - temp.put("range", param); - jsonList.add(temp); - } + if (query.getStartPrice() != null || query.getEndPrice() != null) { + JSONObject param = new JSONObject(); + JSONObject temp = new JSONObject(); + JSONObject temp2 = new JSONObject(); + if (query.getStartPrice() != null) { + temp2.put("gte", query.getStartPrice()); + } + if (query.getEndPrice() != null) { + temp2.put("lte", query.getEndPrice()); + } + param.put("avg_price", temp2); + temp.put("range", param); + jsonList.add(temp); + } - if(StringUtils.isNotBlank(query.getSortField())){ - JSONObject jsonOrder = new JSONObject(); - if(query.getOrder()){ - jsonOrder.put("order", "asc"); - }else{ - jsonOrder.put("order", "desc"); - } - JSONObject jsonSort = new JSONObject(); - jsonSort.put(query.getSortField(), jsonOrder); - List sortJsonList = new ArrayList(); - sortJsonList.add(jsonSort); - reqBody.put("sort", sortJsonList); - } + if (StringUtils.isNotBlank(query.getSortField())) { + JSONObject jsonOrder = new JSONObject(); + if (query.getOrder()) { + jsonOrder.put("order", "asc"); + } else { + jsonOrder.put("order", "desc"); + } + JSONObject jsonSort = new JSONObject(); + jsonSort.put(query.getSortField(), jsonOrder); + List sortJsonList = new ArrayList(); + sortJsonList.add(jsonSort); + reqBody.put("sort", sortJsonList); + } - if(query.getPager().getStartRow() >= 0){ - reqBody.put("from", query.getPager().getStartRow()); - } - if(query.getPager().getPageSize() >= 0){ - reqBody.put("size", query.getPager().getPageSize()); - } + if (query.getPager().getStartRow() >= 0) { + reqBody.put("from", query.getPager().getStartRow()); + } + if (query.getPager().getPageSize() >= 0) { + reqBody.put("size", query.getPager().getPageSize()); + } - if(query.getStatus() != null){ - JSONObject param = new JSONObject(); - param.put("status", query.getStatus()); - JSONObject temp = new JSONObject(); - temp.put("term", param); - jsonList.add(temp); - } + if (query.getStatus() != null) { + JSONObject param = new JSONObject(); + param.put("status", query.getStatus()); + JSONObject temp = new JSONObject(); + temp.put("term", param); + jsonList.add(temp); + } - queryJson.put("must", jsonList); - q.put("bool", queryJson); - reqBody.put("query", q); - //Óû§Ãû:ÃÜÂë - Base64 token = new Base64(); - String authenticationEncoding = token.encodeAsString(new String(""+ES_USER+":"+ES_PASSWORD+"").getBytes()); - HttpRequest request = new HttpRequest(); - Map headers = new HashMap(); - headers.put("Content-Type", "application/json"); - headers.put("Authorization", "Basic "+authenticationEncoding+""); - try { - String response = request.postWithBody("http://es.fangjia.com:9200/"+query.getTable()+"/_search?rest_total_hits_as_int=true", reqBody, headers, "UTF-8"); - JSONObject json = JSONObject.fromObject(response); - long time2 = System.currentTimeMillis(); - System.out.println(time2-time1); - return json; - } catch (HttpRequestException e) { - e.printStackTrace(); - } - return null; - } + queryJson.put("must", jsonList); + ArrayList filterList = new ArrayList(); + if (filter.size() > 0) { + filterList.add(filter); + queryJson.put("filter", filterList); + } + q.put("bool", queryJson); + reqBody.put("query", q); + //Óû§Ãû:ÃÜÂë + Base64 token = new Base64(); + String authenticationEncoding = token.encodeAsString(new String("" + ES_USER + ":" + ES_PASSWORD + "").getBytes()); + HttpRequest request = new HttpRequest(); + Map headers = new HashMap(); + headers.put("Content-Type", "application/json"); + headers.put("Authorization", "Basic " + authenticationEncoding + ""); + try { + String response = request.postWithBody("http://es.fangjia.com:9200/" + query.getTable() + "/_search?rest_total_hits_as_int=true", reqBody, headers, "UTF-8"); + JSONObject json = JSONObject.fromObject(response); + long time2 = System.currentTimeMillis(); + System.out.println(time2 - time1); + return json; + } catch (HttpRequestException e) { + e.printStackTrace(); + } + return null; + } // private List queryList(String id,String category, String city, String region, String name, List alias, // List regionAlias, Integer startDate, Integer endDate, Double startArea, Double endArea, Integer startPrice, Integer endPrice, Integer room, String root,String sort, boolean order, int start, int limit,String table){ @@ -740,188 +795,188 @@ public class SeawaterDaoImpl extends com.fangjia.dal.SeawaterDaoImpl i // return results; // } - private List queryList(SeawaterQuery query){ - JSONObject json = query(query); - if(!json.containsKey("hits") || !json.getJSONObject("hits").containsKey("hits")){ - return null; - } - JSONArray hits = json.getJSONObject("hits").getJSONArray("hits"); - List results = new ArrayList(); - for(int i=0 ;i < hits.size(); i++){ - JSONObject jsonObject = hits.getJSONObject(i); - results.add(jsonObject); - } - return results; - } + private List queryList(SeawaterQuery query) { + JSONObject json = query(query); + if (!json.containsKey("hits") || !json.getJSONObject("hits").containsKey("hits")) { + return null; + } + JSONArray hits = json.getJSONObject("hits").getJSONArray("hits"); + List results = new ArrayList(); + for (int i = 0; i < hits.size(); i++) { + JSONObject jsonObject = hits.getJSONObject(i); + results.add(jsonObject); + } + return results; + } - private int queryCount(String id,String category, String city, String region, String name, List alias, - List regionAlias, Integer startDate, Integer endDate, Integer room, String root,String sort, boolean order, int start, int limit,String table){ - SeawaterQuery query = new SeawaterQuery(); - query.setCat(category); - query.setCityDisplay(city); - query.setRegion(region); - query.setDistrictName(name); - query.setDistrictAlias(alias); - query.setRegionAlias(regionAlias); - query.setStartDate(startDate); - query.setEndDate(endDate); - query.setRoom(room); - query.setRootName(root); - query.setOrder(order); - Pager pager = new Pager(); - pager.setStartRow(start); - pager.setPageSize(limit); - query.setPager(pager); - query.setTable(table); - JSONObject json = query(query); - if(!json.containsKey("hits") || !json.getJSONObject("hits").containsKey("total")){ + private int queryCount(String id, String category, String city, String region, String name, List alias, + List regionAlias, Integer startDate, Integer endDate, Integer room, String root, String sort, boolean order, int start, int limit, String table) { + SeawaterQuery query = new SeawaterQuery(); + query.setCat(category); + query.setCityDisplay(city); + query.setRegion(region); + query.setDistrictName(name); + query.setDistrictAlias(alias); + query.setRegionAlias(regionAlias); + query.setStartDate(startDate); + query.setEndDate(endDate); + query.setRoom(room); + query.setRootName(root); + query.setOrder(order); + Pager pager = new Pager(); + pager.setStartRow(start); + pager.setPageSize(limit); + query.setPager(pager); + query.setTable(table); + JSONObject json = query(query); + if (!json.containsKey("hits") || !json.getJSONObject("hits").containsKey("total")) { return 0; } return json.getJSONObject("hits").getInt("total"); - } + } - private int queryCount(SeawaterQuery query){ - JSONObject json = query(query); - if(!json.containsKey("hits") || !json.getJSONObject("hits").containsKey("total")){ - return 0; - } - return json.getJSONObject("hits").getInt("total"); - } + private int queryCount(SeawaterQuery query) { + JSONObject json = query(query); + if (!json.containsKey("hits") || !json.getJSONObject("hits").containsKey("total")) { + return 0; + } + return json.getJSONObject("hits").getInt("total"); + } - private JSONObject wrapQueryParams(SeawaterQuery query){ - JSONObject reqBody = new JSONObject(); - JSONObject q = new JSONObject(); - JSONObject queryJson = new JSONObject(); - List jsonList = new ArrayList(); - if(StringUtils.isNotBlank(query.getId())) { - JSONObject param = new JSONObject(); - param.put("_id", query.getId()); - JSONObject temp = new JSONObject(); - temp.put("term", param); - jsonList.add(temp); - } - if(StringUtils.isNotBlank(query.getCat())) { - JSONObject param = new JSONObject(); - param.put("cat", query.getCat()); - JSONObject temp = new JSONObject(); - temp.put("term", param); - jsonList.add(temp); - } + private JSONObject wrapQueryParams(SeawaterQuery query) { + JSONObject reqBody = new JSONObject(); + JSONObject q = new JSONObject(); + JSONObject queryJson = new JSONObject(); + List jsonList = new ArrayList(); + if (StringUtils.isNotBlank(query.getId())) { + JSONObject param = new JSONObject(); + param.put("_id", query.getId()); + JSONObject temp = new JSONObject(); + temp.put("term", param); + jsonList.add(temp); + } + if (StringUtils.isNotBlank(query.getCat())) { + JSONObject param = new JSONObject(); + param.put("cat", query.getCat()); + JSONObject temp = new JSONObject(); + temp.put("term", param); + jsonList.add(temp); + } - Set namesList = new LinkedHashSet(); - if(StringUtils.isNotBlank(query.getDistrictName())) { - namesList.add(query.getDistrictName()); - } - if(namesList != null && namesList.size() > 0){ - JSONObject param = new JSONObject(); - param.put("district_name", namesList); - JSONObject temp = new JSONObject(); - temp.put("terms", param); - jsonList.add(temp); - } + Set namesList = new LinkedHashSet(); + if (StringUtils.isNotBlank(query.getDistrictName())) { + namesList.add(query.getDistrictName()); + } + if (namesList != null && namesList.size() > 0) { + JSONObject param = new JSONObject(); + param.put("district_name", namesList); + JSONObject temp = new JSONObject(); + temp.put("terms", param); + jsonList.add(temp); + } - Set regionsList = new LinkedHashSet(); - if(StringUtils.isNotBlank(query.getRegion())) { - regionsList.add(query.getRegion()); - } - if (query.getRegionAlias() != null) { - regionsList.addAll(query.getRegionAlias()); - } - if(regionsList != null && regionsList.size() > 0){ - JSONObject param = new JSONObject(); - param.put("region", regionsList); - JSONObject temp = new JSONObject(); - temp.put("terms", param); - jsonList.add(temp); - } + Set regionsList = new LinkedHashSet(); + if (StringUtils.isNotBlank(query.getRegion())) { + regionsList.add(query.getRegion()); + } + if (query.getRegionAlias() != null) { + regionsList.addAll(query.getRegionAlias()); + } + if (regionsList != null && regionsList.size() > 0) { + JSONObject param = new JSONObject(); + param.put("region", regionsList); + JSONObject temp = new JSONObject(); + temp.put("terms", param); + jsonList.add(temp); + } - if(StringUtils.isNotBlank(query.getCityDisplay())){ - JSONObject param = new JSONObject(); - param.put("city", query.getCityDisplay()); - JSONObject temp = new JSONObject(); - temp.put("term", param); - jsonList.add(temp); - } - if(StringUtils.isNotBlank(query.getEstateType())) { - JSONObject param = new JSONObject(); - param.put("estate_type", query.getEstateType()); - JSONObject temp = new JSONObject(); - temp.put("term", param); - jsonList.add(temp); - } - if(query.getRoom() != null) { - JSONObject param = new JSONObject(); - param.put("room", query.getRoom()); - JSONObject temp = new JSONObject(); - temp.put("term", param); - jsonList.add(temp); - } - if(StringUtils.isNotBlank(query.getRootName())) { - JSONObject param = new JSONObject(); - param.put("root", query.getRootName()); - JSONObject temp = new JSONObject(); - temp.put("term", param); - jsonList.add(temp); - } + if (StringUtils.isNotBlank(query.getCityDisplay())) { + JSONObject param = new JSONObject(); + param.put("city", query.getCityDisplay()); + JSONObject temp = new JSONObject(); + temp.put("term", param); + jsonList.add(temp); + } + if (StringUtils.isNotBlank(query.getEstateType())) { + JSONObject param = new JSONObject(); + param.put("estate_type", query.getEstateType()); + JSONObject temp = new JSONObject(); + temp.put("term", param); + jsonList.add(temp); + } + if (query.getRoom() != null) { + JSONObject param = new JSONObject(); + param.put("room", query.getRoom()); + JSONObject temp = new JSONObject(); + temp.put("term", param); + jsonList.add(temp); + } + if (StringUtils.isNotBlank(query.getRootName())) { + JSONObject param = new JSONObject(); + param.put("root", query.getRootName()); + JSONObject temp = new JSONObject(); + temp.put("term", param); + jsonList.add(temp); + } - if(query.getStartDate() != null || query.getEndDate() != null){ - JSONObject param = new JSONObject(); - JSONObject temp = new JSONObject(); - JSONObject temp2 = new JSONObject(); - if(query.getStartDate() != null){ - temp2.put("gte", query.getStartDate()); - } - if(query.getEndDate() != null){ - temp2.put("lte", query.getEndDate()); - } - param.put("p_date", temp2); - temp.put("range", param); - jsonList.add(temp); - } + if (query.getStartDate() != null || query.getEndDate() != null) { + JSONObject param = new JSONObject(); + JSONObject temp = new JSONObject(); + JSONObject temp2 = new JSONObject(); + if (query.getStartDate() != null) { + temp2.put("gte", query.getStartDate()); + } + if (query.getEndDate() != null) { + temp2.put("lte", query.getEndDate()); + } + param.put("p_date", temp2); + temp.put("range", param); + jsonList.add(temp); + } - if(query.getStartArea() != null || query.getEndArea() != null){ - JSONObject param = new JSONObject(); - JSONObject temp = new JSONObject(); - JSONObject temp2 = new JSONObject(); - if(query.getStartArea() != null){ - temp2.put("gte", query.getStartArea()); - } - if(query.getEndArea() != null){ - temp2.put("lte", query.getEndArea()); - } - param.put("area", temp2); - temp.put("range", param); - jsonList.add(temp); - } + if (query.getStartArea() != null || query.getEndArea() != null) { + JSONObject param = new JSONObject(); + JSONObject temp = new JSONObject(); + JSONObject temp2 = new JSONObject(); + if (query.getStartArea() != null) { + temp2.put("gte", query.getStartArea()); + } + if (query.getEndArea() != null) { + temp2.put("lte", query.getEndArea()); + } + param.put("area", temp2); + temp.put("range", param); + jsonList.add(temp); + } - if(query.getStartPrice() != null || query.getEndPrice() != null){ - JSONObject param = new JSONObject(); - JSONObject temp = new JSONObject(); - JSONObject temp2 = new JSONObject(); - if(query.getStartPrice() != null){ - temp2.put("gte", query.getStartPrice()); - } - if(query.getEndPrice() != null){ - temp2.put("lte", query.getEndPrice()); - } - param.put("avg_price", temp2); - temp.put("range", param); - jsonList.add(temp); - } + if (query.getStartPrice() != null || query.getEndPrice() != null) { + JSONObject param = new JSONObject(); + JSONObject temp = new JSONObject(); + JSONObject temp2 = new JSONObject(); + if (query.getStartPrice() != null) { + temp2.put("gte", query.getStartPrice()); + } + if (query.getEndPrice() != null) { + temp2.put("lte", query.getEndPrice()); + } + param.put("avg_price", temp2); + temp.put("range", param); + jsonList.add(temp); + } - if(query.getStatus() != null){ - JSONObject param = new JSONObject(); - param.put("status", query.getStatus()); - JSONObject temp = new JSONObject(); - temp.put("term", param); - jsonList.add(temp); - } + if (query.getStatus() != null) { + JSONObject param = new JSONObject(); + param.put("status", query.getStatus()); + JSONObject temp = new JSONObject(); + temp.put("term", param); + jsonList.add(temp); + } - queryJson.put("must", jsonList); - q.put("bool", queryJson); - reqBody.put("query", q); - return reqBody; - } + queryJson.put("must", jsonList); + q.put("bool", queryJson); + reqBody.put("query", q); + return reqBody; + } } diff --git a/projects/fangjia-dal/src/main/java/com/fangjia/dal/seawater/model/Seawater.java b/projects/fangjia-dal/src/main/java/com/fangjia/dal/seawater/model/Seawater.java index 15176face..c553d2f46 100644 --- a/projects/fangjia-dal/src/main/java/com/fangjia/dal/seawater/model/Seawater.java +++ b/projects/fangjia-dal/src/main/java/com/fangjia/dal/seawater/model/Seawater.java @@ -6,6 +6,7 @@ import javax.persistence.*; import com.fangjia.dal.DatastoreCategory; import com.fangjia.dal.SeawaterEntity; +import com.fasterxml.jackson.annotation.JsonInclude; @Entity @Table(name = "fangjia.seawater") @@ -35,9 +36,11 @@ public class Seawater implements SeawaterEntity { private String id; private String category; - private int status; + @JsonInclude(JsonInclude.Include.NON_DEFAULT) + private Integer status; private String city; private String region; + private String district; private String districtName; private String address; private Date modificationDate; @@ -46,8 +49,10 @@ public class Seawater implements SeawaterEntity { private String block; private Integer totalPrice; private Double area; + private Double size; private Integer height; private Integer floor; + private Integer maxFloor; private String floorInfo; private String fitment; private Integer room; @@ -55,10 +60,13 @@ public class Seawater implements SeawaterEntity { private Integer toilet; private String mobile; private Integer pDate; + + private String publishDate; private Integer userId; private String url; private String root; private Integer avgPrice; + private Integer unitPrice; private String purpose; private String estateType; private String buildType; @@ -70,6 +78,26 @@ public class Seawater implements SeawaterEntity { private String housingAge; //·¿ÎÝÄêÏÞ Âú¶þÄê private String elevator; //Å䱸µçÌÝ ÓÐ/ÎÞ + private String decoration; + + private Integer distance; + + private String location; + + private String title; + + // ÉÌÆÌ¾­Óª·¶Î§ + private String businessScope; + private String businessRange; + + //ÉÌÆÌÀàÐÍ + private String shopType; + + // д×ÖÂ¥µÈ¼¶ + private String level; + + + @Id @Column(name = "_id") public String getId() { @@ -90,11 +118,11 @@ public class Seawater implements SeawaterEntity { } @Column(name = "status") - public int getStatus() { + public Integer getStatus() { return status; } - public void setStatus(int status) { + public void setStatus(Integer status) { this.status = status; } @@ -206,7 +234,7 @@ public class Seawater implements SeawaterEntity { this.floor = floor; } - @Column(name = "floorInfo") + @Column(name = "floor_info") public String getFloorInfo() { return floorInfo; } @@ -395,4 +423,110 @@ public class Seawater implements SeawaterEntity { public void setElevator(String elevator) { this.elevator = elevator; } + + public String getDistrict() { + return district; + } + + public void setDistrict(String district) { + this.district = district; + } + + public Double getSize() { + return size; + } + + public void setSize(Double size) { + this.size = size; + } + + public Integer getMaxFloor() { + return maxFloor; + } + + public void setMaxFloor(Integer maxFloor) { + this.maxFloor = maxFloor; + } + + public Integer getUnitPrice() { + return unitPrice; + } + + public void setUnitPrice(Integer unitPrice) { + this.unitPrice = unitPrice; + } + + public String getPublishDate() { + return publishDate; + } + + public void setPublishDate(String publishDate) { + this.publishDate = publishDate; + } + + public String getDecoration() { + return decoration; + } + + public void setDecoration(String decoration) { + this.decoration = decoration; + } + + public Integer getDistance() { + return distance; + } + + public void setDistance(Integer distance) { + this.distance = distance; + } + + public String getLocation() { + return location; + } + + public void setLocation(String location) { + this.location = location; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getBusinessScope() { + return businessScope; + } + + public void setBusinessScope(String businessScope) { + this.businessScope = businessScope; + } + + public String getShopType() { + return shopType; + } + + public void setShopType(String shopType) { + this.shopType = shopType; + } + + @Column(name = "level") + public String getLevel() { + return level; + } + + public void setLevel(String level) { + this.level = level; + } + + @Column(name = "business_range") + public String getBusinessRange() { + return businessRange; + } + + public void setBusinessRange(String businessRange) { + this.businessRange = businessRange; + } } diff --git a/projects/fangjia-dal/src/main/java/com/fangjia/dal/seaweed/model/Seaweed.java b/projects/fangjia-dal/src/main/java/com/fangjia/dal/seaweed/model/Seaweed.java index daa27c20e..6fbd24813 100644 --- a/projects/fangjia-dal/src/main/java/com/fangjia/dal/seaweed/model/Seaweed.java +++ b/projects/fangjia-dal/src/main/java/com/fangjia/dal/seaweed/model/Seaweed.java @@ -24,6 +24,8 @@ public class Seaweed implements SeaweedEntity { private List alias; private List addrAlias; + private double score; + @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "_id") @@ -134,4 +136,13 @@ public class Seaweed implements SeaweedEntity { public void setEstateType2(String estateType2) { this.estateType2 = estateType2; } + + @Transient + public double getScore() { + return score; + } + + public void setScore(double score) { + this.score = score; + } } diff --git a/projects/fangjia-dal/src/main/java/com/fangjia/dal/sql/model/ApiUser.java b/projects/fangjia-dal/src/main/java/com/fangjia/dal/sql/model/ApiUser.java index 95216319c..216e0d6cb 100644 --- a/projects/fangjia-dal/src/main/java/com/fangjia/dal/sql/model/ApiUser.java +++ b/projects/fangjia-dal/src/main/java/com/fangjia/dal/sql/model/ApiUser.java @@ -28,6 +28,10 @@ public class ApiUser implements SqlEntity { private String company; private int isTest; //0-Õýʽ¿Í‘ô 1-²âÊÔÓû§ 2-ÄÚ²¿²âÊÔÓû§ private Date deadTime; + + private String contact; //ÁªÏµÈË + + private String phone; //ÁªÏµÈËÊÖ»úºÅ /** * ÕË»§ÓÃ; * 1£ºOpen APi @@ -41,6 +45,12 @@ public class ApiUser implements SqlEntity { private Integer isMonitor; + private Integer isMonitorStatistic; + + private Integer isMonitorUsed; + + private Integer isWarnExpired; + @Id @Column(name = "ID") public long getId() { @@ -185,4 +195,49 @@ public class ApiUser implements SqlEntity { public void setIsMonitor(Integer isMonitor) { this.isMonitor = isMonitor; } + + @Column(name = "CUSTOMER_CONTACT") + public String getContact() { + return contact; + } + + public void setContact(String contact) { + this.contact = contact; + } + + @Column(name = "CUSTOMER_CONTACT_MOBILE") + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + + @Column(name = "IS_MONITOR_STATISTIC") + public Integer getIsMonitorStatistic() { + return isMonitorStatistic; + } + + public void setIsMonitorStatistic(Integer isMonitorStatistic) { + this.isMonitorStatistic = isMonitorStatistic; + } + + @Column(name = "IS_MONITOR_USED") + public Integer getIsMonitorUsed() { + return isMonitorUsed; + } + + public void setIsMonitorUsed(Integer isMonitorUsed) { + this.isMonitorUsed = isMonitorUsed; + } + + @Column(name = "IS_WARN_EXPIRED") + public Integer getIsWarnExpired() { + return isWarnExpired; + } + + public void setIsWarnExpired(Integer isWarnExpired) { + this.isWarnExpired = isWarnExpired; + } } diff --git a/projects/fangjia-dal/src/main/java/com/fangjia/dal/sql/model/FjtEvaluation.java b/projects/fangjia-dal/src/main/java/com/fangjia/dal/sql/model/FjtEvaluation.java index 4b72f411c..90af3ec7e 100644 --- a/projects/fangjia-dal/src/main/java/com/fangjia/dal/sql/model/FjtEvaluation.java +++ b/projects/fangjia-dal/src/main/java/com/fangjia/dal/sql/model/FjtEvaluation.java @@ -92,6 +92,8 @@ public class FjtEvaluation implements SqlEntity{ private String contact; private String reportNum; private Double carSiteArea; + + private Integer carSitePrice; // ³µÎ»¼Û private String source; private String accountChecker; private String floorDesc; //±ðÊûÂ¥²ãÃèÊö @@ -783,6 +785,15 @@ public class FjtEvaluation implements SqlEntity{ this.loan = loan; } + @Column(name = "car_site_price") + public Integer getCarSitePrice() { + return carSitePrice; + } + + public void setCarSitePrice(Integer carSitePrice) { + this.carSitePrice = carSitePrice; + } + @Override public String toString() { return "FjtEvaluation{" + diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/HttpStatusCodeEnum.java b/projects/fangjia-open/src/main/java/com/fangjia/open/HttpStatusCodeEnum.java index 402218d72..a20704090 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/HttpStatusCodeEnum.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/HttpStatusCodeEnum.java @@ -8,7 +8,8 @@ public enum HttpStatusCodeEnum { BAD_REQUEST_DECRYPT_ERROR(4002,"¼ÓÃܲÎÊý½âÃÜʧ°Ü"), UN_AUTHORIZED(401,"ÇëÇóδ±»ÊÚȨ"), SERVER_ERROR(500,"·þÎñÆ÷ÄÚ²¿´íÎó"), - SERVER_FORBID(403,"ÇëÇ󯵷±"); + SERVER_FORBID(403,"ÇëÇ󯵷±"), + UPGRADE(503,"·þÎñÉý¼¶ÖÐ"); private final int code; private final String msg; diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/AddrSvcController.java b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/AddrSvcController.java index 28f780026..118cf497c 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/AddrSvcController.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/AddrSvcController.java @@ -1,10 +1,13 @@ package com.fangjia.open.controllers; import com.fangjia.core.util.HttpRequest; -import com.fangjia.dal.common.DistrictKey; import com.fangjia.dal.mongo.model.VillageIdentify; import com.fangjia.dal.seaweed.model.District; -import com.fangjia.open.dto.addressGovernance.*; +import com.fangjia.open.APIConstant; +import com.fangjia.open.dto.addressGovernance.DistrictDto; +import com.fangjia.open.dto.addressGovernance.DistrictIdentifyDto; +import com.fangjia.open.dto.addressGovernance.MatchedBuildingDto; +import com.fangjia.open.dto.addressGovernance.StructureAndCompleteDto; import com.fangjia.open.interceptors.Authority; import com.fangjia.open.interceptors.Role; import com.fangjia.open.model.AddesssMatchModel; @@ -12,7 +15,7 @@ import com.fangjia.open.model.AddressModel; import com.fangjia.open.model.BasicModel; import com.fangjia.open.model.RestfulModelAndView; import com.fangjia.open.util.CommonDtoUtils; -import com.fangjia.service.bo.DistrictStatBo; +import com.fangjia.service.bo.DistrictAvgBo; import com.fangjia.service.datastore.DistrictService; import com.fangjia.service.district.DistrictStatService; import com.fangjia.service.mongo.fangjia.VillageIdentifyService; @@ -20,6 +23,7 @@ import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; +import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpEntity; @@ -38,13 +42,9 @@ import sun.misc.BASE64Encoder; import java.io.IOException; import java.net.Authenticator; -import java.net.InetSocketAddress; import java.net.PasswordAuthentication; -import java.net.Proxy; import java.nio.charset.Charset; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; /** * µØÖ·ÖÎÀí @@ -78,14 +78,17 @@ public class AddrSvcController { Map params = new HashMap(); params.put("city", model.getCity()); params.put("address", model.getAddress()); + params.put("addressAssessment", "true"); try { - json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/structure/v2", params, "UTF-8"); + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/formatNinelevel", params, "UTF-8"); if (json != null) { int code = json.getInt("status"); String msg = json.getString("msg"); - BasicModel basicModel = new BasicModel(code, msg); + BasicModel basicModel = new BasicModel(code == 0 ? 200 : 0, msg); if (json.containsKey("result")) { - basicModel.setResult(CommonDtoUtils.transformV(StructureDto.class, json.get("result"))); + JSONObject result = json.getJSONObject("result"); + result.remove("formatAddress"); + basicModel.setResult(result); } mav.setModel(basicModel); } else { @@ -118,13 +121,27 @@ public class AddrSvcController { params.put("city", model.getCity()); params.put("address", model.getAddress()); try { - json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/fiveDivisionStructure/v2", params, "UTF-8"); + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/villageIdentify", params, "UTF-8"); if (json != null) { int code = json.getInt("status"); String msg = json.getString("msg"); - BasicModel basicModel = new BasicModel(code, msg); + BasicModel basicModel = new BasicModel(code == 0 ? 200 : 0, msg); if (json.containsKey("result")) { - basicModel.setResult(CommonDtoUtils.transformV(DistrictIdentifyDto.class, json.get("result"))); + DistrictIdentifyDto districtIdentifyDto = CommonDtoUtils.transformV(DistrictIdentifyDto.class, json.get("result")); + JSONObject result = json.getJSONObject("result"); + if (result.containsKey("town")) { + districtIdentifyDto.setTownship(result.getString("town")); + } + if (result.containsKey("townCode")) { + districtIdentifyDto.setTownshipCode(result.getString("townCode")); + } + if (result.containsKey("committee")) { + districtIdentifyDto.setCommunity(result.getString("committee")); + } + if (result.containsKey("committeeCode")) { + districtIdentifyDto.setCommunityCode(result.getString("committeeCode")); + } + basicModel.setResult(districtIdentifyDto); } mav.setModel(basicModel); } else { @@ -158,7 +175,7 @@ public class AddrSvcController { try { json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/structureAndComplete", params, "UTF-8"); if (json != null) { - int code = json.getInt("status"); + int code = json.getInt("status") == 0 ? 200 : 0; String msg = json.getString("msg"); BasicModel basicModel = new BasicModel(code, msg); if (json.containsKey("result")) { @@ -234,6 +251,10 @@ public class AddrSvcController { json = request.getJsonContent("http://192.168.0.100:32080/FangJiaNlpService/match", params, "UTF-8"); BasicModel basicModel = new BasicModel(200, "ok"); if (json != null && json.size() > 0) { + // ·Ç³¬¼¶Óû§²»·µ»ØÖÃÐÅ¶È + if (json.containsKey("credit") && !APIConstant.SUPER_USER_TOKEN.equals(model.getToken())) { + json.remove("credit"); + } basicModel.setResult(CommonDtoUtils.transformV(MatchedBuildingDto.class, json)); } mav.setModel(basicModel); @@ -252,10 +273,11 @@ public class AddrSvcController { public Object suggestionAction(AddressModel model) { RestfulModelAndView mav = new RestfulModelAndView(); - if (StringUtils.isBlank(model.getCity())) { - mav.setModel(BasicModel.buildBadRequestModel("³ÇÊв»ÄÜΪ¿Õ")); - return mav; - } + // ³ÇÊиÄΪ·Ç±ØÌî +// if (StringUtils.isBlank(model.getCity())) { +// mav.setModel(BasicModel.buildBadRequestModel("³ÇÊв»ÄÜΪ¿Õ")); +// return mav; +// } if (StringUtils.isBlank(model.getKeywords())) { mav.setModel(BasicModel.buildBadRequestModel("¹Ø¼ü×Ö²»ÄÜΪ¿Õ")); return mav; @@ -265,20 +287,60 @@ public class AddrSvcController { JSONObject json = null; Map params = new HashMap(); params.put("city", model.getCity()); - params.put("region", model.getRegion()); + params.put("district", model.getDistrict()); params.put("keywords", model.getKeywords()); params.put("page", "0"); - params.put("size", String.valueOf(model.getMax() == 0 ? 20 : (model.getMax() > 100 ? 100 : model.getMax()))); + params.put("offset", String.valueOf(model.getMax() == 0 ? 10 : (model.getMax() > 100 ? 100 : model.getMax()))); try { - json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/addressAssociation2", params, "UTF-8"); + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/v2/addressAssociation", params, "UTF-8"); if (json != null) { - int code = json.getInt("status"); + int code = json.getInt("msgCode"); String msg = json.getString("msg"); BasicModel basicModel = new BasicModel(code, msg); if (json.containsKey("result")) { - JSONObject result = (JSONObject.fromObject(json.get("result"))); - if (result.getInt("totalElements") > 0) { - basicModel.setResult(CommonDtoUtils.transformListV(DistrictDto.class, result.getJSONArray("content"))); + JSONArray jsonArray = json.getJSONArray("result"); + if (jsonArray.size() > 0) { + basicModel.setResult(CommonDtoUtils.transformListV(DistrictDto.class, jsonArray)); + } + } + mav.setModel(basicModel); + } else { + mav.setModel(BasicModel.buildServerErrorModel().setMsg("·þÎñÉý¼¶ÖÐ...")); + } + } catch (Exception e) { + e.printStackTrace(); + mav.setModel(BasicModel.buildServerErrorModel().setMsg("·þÎñÉý¼¶ÖÐ...")); + } + return mav; + } + + /** + * µØÖ·ÁªÏë + */ + public Object tipsAction(AddressModel model) { + + RestfulModelAndView mav = new RestfulModelAndView(); + if (StringUtils.isBlank(model.getKeywords())) { + mav.setModel(BasicModel.buildBadRequestModel("ËÑË÷¹Ø¼ü×Ö²»ÄÜΪ¿Õ")); + return mav; + } + + HttpRequest request = new HttpRequest(); + JSONObject json = null; + Map params = new HashMap(); + params.put("keywords", model.getKeywords()); + params.put("city", StringUtils.isNotBlank(model.getCity()) ? model.getCity() : ""); + params.put("max", model.getMax() != 0 ? String.valueOf(model.getMax()) : ""); + try { + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/tips", params, "UTF-8"); + if (json != null) { + int code = json.getInt("msgCode"); + String msg = json.getString("msg"); + BasicModel basicModel = new BasicModel(code, msg); + if (json.containsKey("result")) { + JSONArray jsonArray = json.getJSONArray("result"); + if (jsonArray.size() > 0) { + basicModel.setResult(jsonArray); } } mav.setModel(basicModel); @@ -312,18 +374,26 @@ public class AddrSvcController { json = request.getJsonContent("http://192.168.0.100:32080/FangJiaNlpService/match", params, "UTF-8"); BasicModel basicModel = new BasicModel(200, "ok"); if (json != null && json.size() > 0) { - MatchedBuildingDto dto = CommonDtoUtils.transformV(MatchedBuildingDto.class, json); + MatchedBuildingDto dto = new MatchedBuildingDto(); + if (json.containsKey("id")) { + dto.setId(json.getString("id")); + } + if (json.containsKey("city")) { + dto.setCity(json.getString("city")); + } + if (json.containsKey("district")) { + dto.setDistrict(json.getString("district")); + } + if (json.containsKey("name")) { + dto.setName(json.getString("name")); + } District district = districtService.findByNameAndAlias(dto.getCity(), dto.getDistrict(), dto.getName(), "district"); if (null != district) { - DistrictStatBo statBo = districtStatService.findCurrentDistrictStat(new DistrictKey(dto.getCity(), dto.getDistrict(), dto.getName())); + //DistrictStatBo statBo = districtStatService.findCurrentDistrictStat(new DistrictKey(dto.getCity(), dto.getDistrict(), dto.getName())); + DistrictAvgBo statBo = districtStatService.findDistrictStat(district, "district", null); if (null != statBo) { - if (statBo.getDistrictStat() != null) { - dto.setAvgPrice(statBo.getDistrictStat().getAvgPrice()); - } else if (statBo.getVillaDistrictStat() != null) { - dto.setAvgPrice(statBo.getVillaDistrictStat().getAvgPrice()); - } - + dto.setAvgPrice(statBo.getAvgPrice()); } } basicModel.setResult(dto); @@ -446,7 +516,7 @@ public class AddrSvcController { } else { try { //Èç¹ûÊǽ­ËÕÊ¡»òÕßÕã½­Ê¡ µ÷ÓÃÆëÁºµÄ½á¹û - if ("½­ËÕÊ¡".equals(result.getString("province")) || "Õã½­Ê¡".equals(result.getString("province"))) { + if (result.containsKey("province") && ("½­ËÕÊ¡".equals(result.getString("province")) || "Õã½­Ê¡".equals(result.getString("province")))) { //½á¹û±È½Ï£¬Èç¹ûɿũ½á¹û²»Ò»Ö //µ÷ÓÃÆëÁº type £º1 ¶Ô¹« 0 ¶Ô˽ //ÎÒÃÇ type £º1 ¶Ô˽ 2 ¶Ô¹² @@ -513,7 +583,7 @@ public class AddrSvcController { if (map.get("city").endsWith("Çø")) { return "·ñ"; } - if (map.get("city").equals("¶«Ý¸ÊÐ") || map.get("city").equals("¼ÎÓø¹ØÊÐ") || map.get("city").equals("ÖÐɽÊÐ") || map.get("city").equals("ÙÙÖÝÊÐ") ) { + if (map.get("city").equals("¶«Ý¸ÊÐ") || map.get("city").equals("¼ÎÓø¹ØÊÐ") || map.get("city").equals("ÖÐɽÊÐ") || map.get("city").equals("ÙÙÖÝÊÐ")) { return "·ñ"; } return "ÊÇ"; @@ -526,7 +596,7 @@ public class AddrSvcController { * @return */ public String addrArea(Map map, String type) { - if (map.get("verifyFlag") == null ) { + if (map.get("verifyFlag") == null) { return ""; } if (map.get("verifyFlag").equals("·ÇÅ©")) { @@ -645,6 +715,362 @@ public class AddrSvcController { return mav; } + /** + * ¶Ô¹«ÉæÅ©Ê¶±ð-йæÔò-ÉϺ£ÒøÐÐ + * + * @param model + * @return + */ + public Object boscEnterpriseVillageIdentifyAction(AddressModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + if (StringUtils.isBlank(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("µØÖ·²»ÄÜΪ¿Õ")); + return mav; + } + + HttpRequest request = new HttpRequest(); + JSONObject json = null; + Map params = new HashMap(); + params.put("city", StringUtils.isNotBlank(model.getCity()) ? model.getCity() : null); + String address = model.getAddress(); + params.put("address", address); + try { + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/boscEnterpriseVillageIdentify", params, "UTF-8"); + } catch (Exception e) { + try { + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/boscEnterpriseVillageIdentify", params, "UTF-8"); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + if (json != null) { + if (json.containsKey("result")) { + int code = json.getInt("msgCode"); + String msg = json.getString("msg"); + BasicModel basicModel = new BasicModel(code, msg); + HashMap map = new LinkedHashMap(); + //ÎÒÃǵĽá¹û +// "province": "½­ËÕÊ¡", +// "city": "ËÕÖÝÊÐ", +// "district": "À¥É½ÊÐ", +// "town": "ÓñɽÕò", +// "committee": "ÄÏÐÇä´åί»á", +// "provinceCode": "320000000000", +// "cityCode": "320500000000", +// "districtCode": "320583000000", +// "townCode": "320583100000", +// "committeeCode": "320583100222", +// "typeCode": "220", +// "typeName": "´åׯ", +// "verifyFlag": "·ÇÅ©", +// "addrVerify": "µØÖ·ÓÐЧ", +// "countyLevelCity": "ÊÇ", +// "administrativeTowns": "·ñ", +// "countyGov": "·ñ", +// "devDistrict": "ÊÇ", +// "devDistrictName": "À¥É½¸ßм¼Êõ²úÒµ¿ª·¢Çø", +// "devLevel": "¹ú¼Ò¼¶", +// "addrArea": "¿ª·¢Çø", +// "countyGovTown": "À¥É½¿ª·¢Çø" + JSONObject result = json.getJSONObject("result"); + if (result.containsKey("province")) { + map.put("province", result.getString("province")); + } + if (result.containsKey("city")) { + map.put("city", result.getString("city")); + } + if (result.containsKey("district")) { + map.put("district", result.getString("district")); + } + if (result.containsKey("town")) { + map.put("town", result.getString("town")); + } + if (result.containsKey("committee")) { + map.put("committee", result.getString("committee")); + } + if (result.containsKey("provinceCode")) { + map.put("provinceCode", result.getString("provinceCode")); + } + if (result.containsKey("cityCode")) { + map.put("cityCode", result.getString("cityCode")); + } + if (result.containsKey("districtCode")) { + map.put("districtCode", result.getString("districtCode")); + } + if (result.containsKey("townCode")) { + map.put("townCode", result.getString("townCode")); + } + if (result.containsKey("committeeCode")) { + map.put("committeeCode", result.getString("committeeCode")); + } + if (result.containsKey("typeCode")) { + map.put("typeCode", result.getString("typeCode")); + } + if (result.containsKey("typeName")) { + map.put("typeName", result.getString("typeName")); + } + if (result.containsKey("verifyFlag")) { + map.put("verifyFlag", result.getString("verifyFlag")); + } + if (result.containsKey("addrVerify")) { + map.put("addrVerify", result.getString("addrVerify")); + } + if (result.containsKey("countyLevelCity")) { + map.put("countyLevelCity", result.getString("countyLevelCity")); + } + if (result.containsKey("administrativeTowns")) { + map.put("administrativeTowns", result.getString("administrativeTowns")); + } + if (result.containsKey("countyGov")) { + map.put("countyGov", result.getString("countyGov")); + } + if (result.containsKey("devDistrict")) { + map.put("devDistrict", result.getString("devDistrict")); + } + if (result.containsKey("devLevel")) { + map.put("devLevel", result.getString("devLevel")); + } + + if (result.containsKey("addrArea")) { + map.put("addrArea", result.getString("addrArea")); + } + if (result.containsKey("devDistrictName")) { + map.put("devDistrictName", result.getString("devDistrictName")); + } + if (result.containsKey("countyGovTown")) { + map.put("countyGovTown", result.getString("countyGovTown")); + } + basicModel.setResult(map); + mav.setModel(basicModel); + } else { + mav.setModel(BasicModel.buildServerErrorModel().setMsg("·þÎñÉý¼¶ÖÐ...")); + } + } + return mav; + } + + /** + * ¶ÔË½ÉæÅ©Ê¶±ð + */ + public Object residentialVillageIdentifyAction(AddressModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + if (StringUtils.isBlank(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("µØÖ·²»ÄÜΪ¿Õ")); + return mav; + } + + HttpRequest request = new HttpRequest(); + JSONObject json = null; + Map params = new HashMap(); + params.put("city", StringUtils.isNotBlank(model.getCity()) ? model.getCity() : null); + String address = model.getAddress(); + params.put("address", address); + String type = StringUtils.isNotBlank(model.getType()) ? model.getType() : null; + // ¶Ô¹« + model.setType("1"); + String villageType = "2".equals(model.getType()) ? "¶Ô¹«" : "¶Ô˽"; + params.put("type", type); + params.put("showFullValue", "2"); + Pager pager = new Pager(1, 1); + List villageIdentifyList = villageIdentifyService.findByCityAndAddress(villageType, model.getCity(), model.getAddress(), pager); + VillageIdentify villageResult = CollectionUtils.isNotEmpty(villageIdentifyList) ? villageIdentifyList.get(0) : null; + if (villageResult != null && StringUtils.isNotBlank(villageResult.getVerifyFlag())) { + Map resultMap = new HashMap(); + resultMap.put("province", villageResult.getProvince()); + resultMap.put("city", villageResult.getCity1()); + resultMap.put("district", villageResult.getDistrict()); + resultMap.put("town", villageResult.getTown()); + resultMap.put("committee", villageResult.getCommittee()); + resultMap.put("provinceCode", villageResult.getCityCode()); + resultMap.put("cityCode", villageResult.getCityCode()); + resultMap.put("districtCode", villageResult.getDistrictCode()); + resultMap.put("townCode", villageResult.getTownCode()); + resultMap.put("committeeCode", villageResult.getCommitteeCode()); + resultMap.put("typeCode", villageResult.getTypeCode()); + resultMap.put("typeName", villageResult.getTypeName()); + resultMap.put("verifyFlag", villageResult.getVerifyFlag()); + resultMap.put("addrVerify", villageResult.getAddrVerify()); + resultMap.put("countyLevelCity", villageResult.getCountyLevelCity()); + resultMap.put("administrativeTowns", villageResult.getAdministrativeTowns()); + resultMap.put("countyGov", villageResult.getCountyGov()); + resultMap.put("devDistrict", villageResult.getDevDistrict()); + resultMap.put("devDistrictName", villageResult.getDevDistrictName()); + resultMap.put("devLevel", villageResult.getDevLevel()); + resultMap.put("addrArea", villageResult.getAddrArea()); + BasicModel basicModel = new BasicModel(200, "OK"); + basicModel.setResult(resultMap); + mav.setModel(basicModel); + } else { +// params.put("showTestValue", "2"); + Integer radius = model.getRadius(); + params.put("radius", (radius != null && radius != 0) ? radius.toString() : null); + try { + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/residentialVillageIdentify", params, "UTF-8"); + } catch (Exception e) { + try { + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/residentialVillageIdentify", params, "UTF-8"); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + if (json != null) { + int code = json.getInt("msgCode"); + String msg = json.getString("msg"); + BasicModel basicModel = new BasicModel(code, msg); + if (json.containsKey("result")) { + //ÎÒÃǵĽá¹û + JSONObject result = json.getJSONObject("result"); + basicModel.setResult(result); + } + mav.setModel(basicModel); + } else { + mav.setModel(BasicModel.buildServerErrorModel().setMsg("·þÎñÉý¼¶ÖÐ...")); + } + } + return mav; + } + + /** + * ¶Ô¹«ÉæÅ©Ê¶±ð + */ + public Object enterpriseVillageIdentifyAction(AddressModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + if (StringUtils.isBlank(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("µØÖ·²»ÄÜΪ¿Õ")); + return mav; + } + + HttpRequest request = new HttpRequest(); + JSONObject json = null; + Map params = new HashMap(); + params.put("city", StringUtils.isNotBlank(model.getCity()) ? model.getCity() : null); + String address = model.getAddress(); + params.put("address", address); + String type = StringUtils.isNotBlank(model.getType()) ? model.getType() : null; + // ¶Ô¹« + model.setType("2"); + String villageType = "2".equals(model.getType()) ? "¶Ô¹«" : "¶Ô˽"; + params.put("type", type); + params.put("showFullValue", "2"); + Pager pager = new Pager(1, 1); + List villageIdentifyList = villageIdentifyService.findByCityAndAddress(villageType, model.getCity(), model.getAddress(), pager); + VillageIdentify villageResult = CollectionUtils.isNotEmpty(villageIdentifyList) ? villageIdentifyList.get(0) : null; + if (villageResult != null && StringUtils.isNotBlank(villageResult.getVerifyFlag())) { + Map resultMap = new HashMap(); + resultMap.put("province", villageResult.getProvince()); + resultMap.put("city", villageResult.getCity1()); + resultMap.put("district", villageResult.getDistrict()); + resultMap.put("town", villageResult.getTown()); + resultMap.put("committee", villageResult.getCommittee()); + resultMap.put("provinceCode", villageResult.getCityCode()); + resultMap.put("cityCode", villageResult.getCityCode()); + resultMap.put("districtCode", villageResult.getDistrictCode()); + resultMap.put("townCode", villageResult.getTownCode()); + resultMap.put("committeeCode", villageResult.getCommitteeCode()); + resultMap.put("typeCode", villageResult.getTypeCode()); + resultMap.put("typeName", villageResult.getTypeName()); + resultMap.put("verifyFlag", villageResult.getVerifyFlag()); + resultMap.put("addrVerify", villageResult.getAddrVerify()); + resultMap.put("countyLevelCity", villageResult.getCountyLevelCity()); + resultMap.put("administrativeTowns", villageResult.getAdministrativeTowns()); + resultMap.put("countyGov", villageResult.getCountyGov()); + resultMap.put("devDistrict", villageResult.getDevDistrict()); + resultMap.put("devDistrictName", villageResult.getDevDistrictName()); + resultMap.put("devLevel", villageResult.getDevLevel()); + resultMap.put("addrArea", villageResult.getAddrArea()); + BasicModel basicModel = new BasicModel(200, "OK"); + basicModel.setResult(resultMap); + mav.setModel(basicModel); + } else { +// params.put("showTestValue", "2"); + Integer radius = model.getRadius(); + params.put("radius", (radius != null && radius != 0) ? radius.toString() : null); + try { + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/enterpriseVillageIdentify", params, "UTF-8"); + } catch (Exception e) { + try { + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/enterpriseVillageIdentify", params, "UTF-8"); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + + if (json != null) { + int code = json.getInt("msgCode"); + String msg = json.getString("msg"); + BasicModel basicModel = new BasicModel(code, msg); + if (json.containsKey("result")) { + //ÎÒÃǵĽá¹û + JSONObject result = json.getJSONObject("result"); + //ÎÒÃÇÊ¡¼¶¼°ÒÔÉÏÓпª·¢Çø£¬Ö±½ÓÓÃÎÒÃǵĽá¹û + if (result.containsKey("devDistrictName")) { + basicModel.setResult(result); + } else if (!"2".equals(type)) { // ¶Ô˽µÄ²»ÓÃÆëÁº + basicModel.setResult(result); + } else { + try { + //Èç¹ûÊǽ­ËÕÊ¡»òÕßÕã½­Ê¡ µ÷ÓÃÆëÁºµÄ½á¹û + if ("½­ËÕÊ¡".equals(result.getString("province")) || "Õã½­Ê¡".equals(result.getString("province"))) { + + //½á¹û±È½Ï£¬Èç¹ûɿũ½á¹û²»Ò»Ö + //µ÷ÓÃÆëÁº type £º1 ¶Ô¹« 0 ¶Ô˽ + //ÎÒÃÇ type £º1 ¶Ô˽ 2 ¶Ô¹² + String qltype = "2".equals(type) ? "1" : "0"; + Map map = senRequest(address, qltype); + // ɿũ½á¹û²»Ò»Ñù + if (!map.get("verifyFlag").equals(result.get("verifyFlag"))) { + // ÆëÁºÏØÕþ¸®µ«ÊÇÉæÅ©ÎªÅ©£¬È¡ÎÒÃǵĽá¹û ÑïÖÐÊÐÈýé½ÖµÀÖлª´åÓÀ¹ÌºÓ·1ºÅ + if ("ÊÇ".equals(map.get("countyGov")) && "Å©".equals(map.get("verifyFlag"))) { + basicModel.setResult(result); + mav.setModel(basicModel); + return mav; + } + //ÓÐÊÐϽ½¨ÖÆÕò, »òÕß³ÇÊв»Ò»Ñù ÓÃÎÒÃÇ + if (result.containsKey("city")) { + if ("ÊÇ".equals(result.get("administrativeTowns")) || (!result.get("city").equals(map.get("city")) && StringUtils.isNotBlank(result.getString("city")))) { + basicModel.setResult(result); + } else { + map.put("addrVerify", "µØÖ·ÓÐЧ"); + map.put("addrArea", addrArea(map, type)); + map.put("countyLevelCity", countyLevelCity(map)); + map.put("typeName", areaMap.get(map.get("typeCode"))); + basicModel.setResult(map); + } + } else { + map.put("addrVerify", "µØÖ·ÓÐЧ"); + map.put("addrArea", addrArea(map, type)); + map.put("countyLevelCity", countyLevelCity(map)); + map.put("typeName", areaMap.get(map.get("typeCode"))); + basicModel.setResult(map); + } + + } else { + basicModel.setResult(result); + } + + } else { + basicModel.setResult(result); + + } + + } catch (Exception e) { + e.printStackTrace(); + basicModel.setResult(result); + } + + } + + } + mav.setModel(basicModel); + } else { + mav.setModel(BasicModel.buildServerErrorModel().setMsg("·þÎñÉý¼¶ÖÐ...")); + } + } + return mav; + } /** * ÉæÅ©Ê¶±ð-йæÔò-»ù´¡°æ±¾ @@ -675,27 +1101,27 @@ public class AddrSvcController { VillageIdentify villageResult = CollectionUtils.isNotEmpty(villageIdentifyList) ? villageIdentifyList.get(0) : null; if (villageResult != null && StringUtils.isNotBlank(villageResult.getVerifyFlag())) { Map resultMap = new HashMap(); - resultMap.put("province",villageResult.getProvince()); - resultMap.put("city",villageResult.getCity1()); - resultMap.put("district",villageResult.getDistrict()); - resultMap.put("town",villageResult.getTown()); - resultMap.put("committee",villageResult.getCommittee()); - resultMap.put("provinceCode",villageResult.getCityCode()); - resultMap.put("cityCode",villageResult.getCityCode()); - resultMap.put("districtCode",villageResult.getDistrictCode()); - resultMap.put("townCode",villageResult.getTownCode()); - resultMap.put("committeeCode",villageResult.getCommitteeCode()); - resultMap.put("typeCode",villageResult.getTypeCode()); - resultMap.put("typeName",villageResult.getTypeName()); - resultMap.put("verifyFlag",villageResult.getVerifyFlag()); + resultMap.put("province", villageResult.getProvince()); + resultMap.put("city", villageResult.getCity1()); + resultMap.put("district", villageResult.getDistrict()); + resultMap.put("town", villageResult.getTown()); + resultMap.put("committee", villageResult.getCommittee()); + resultMap.put("provinceCode", villageResult.getCityCode()); + resultMap.put("cityCode", villageResult.getCityCode()); + resultMap.put("districtCode", villageResult.getDistrictCode()); + resultMap.put("townCode", villageResult.getTownCode()); + resultMap.put("committeeCode", villageResult.getCommitteeCode()); + resultMap.put("typeCode", villageResult.getTypeCode()); + resultMap.put("typeName", villageResult.getTypeName()); + resultMap.put("verifyFlag", villageResult.getVerifyFlag()); resultMap.put("addrVerify", villageResult.getAddrVerify()); - resultMap.put("countyLevelCity",villageResult.getCountyLevelCity()); - resultMap.put("administrativeTowns",villageResult.getAdministrativeTowns()); - resultMap.put("countyGov",villageResult.getCountyGov()); - resultMap.put("devDistrict",villageResult.getDevDistrict()); - resultMap.put("devDistrictName",villageResult.getDevDistrictName()); - resultMap.put("devLevel",villageResult.getDevLevel()); - resultMap.put("addrArea",villageResult.getAddrArea()); + resultMap.put("countyLevelCity", villageResult.getCountyLevelCity()); + resultMap.put("administrativeTowns", villageResult.getAdministrativeTowns()); + resultMap.put("countyGov", villageResult.getCountyGov()); + resultMap.put("devDistrict", villageResult.getDevDistrict()); + resultMap.put("devDistrictName", villageResult.getDevDistrictName()); + resultMap.put("devLevel", villageResult.getDevLevel()); + resultMap.put("addrArea", villageResult.getAddrArea()); BasicModel basicModel = new BasicModel(200, "OK"); basicModel.setResult(resultMap); mav.setModel(basicModel); @@ -950,6 +1376,7 @@ public class AddrSvcController { * @param model * @return */ + @Deprecated public Object addressAssociationAction(AddressModel model) { RestfulModelAndView mav = new RestfulModelAndView(); @@ -994,6 +1421,286 @@ public class AddrSvcController { return mav; } + /** + * Êм¶ÐÐÕþÇø»®²éѯ½Ó¿Ú + * + * @param model + * @return + */ + public Object listCityAction(AddressModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + HttpRequest request = new HttpRequest(); + JSONObject json = null; + Map params = new HashMap(); + params.put("province", StringUtils.isNotBlank(model.getProvince()) ? model.getProvince() : null); + try { + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/listCity", params, "UTF-8"); + } catch (Exception e) { + try { + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/listCity", params, "UTF-8"); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + if (json != null) { + int code = json.getInt("msgCode"); + String msg = json.getString("msg"); + BasicModel basicModel = new BasicModel(code, msg); + List> list = new ArrayList>(); + if (json.containsKey("result")) { + JSONArray jsonArray = json.getJSONArray("result"); + if (jsonArray != null) { + for (Object o : jsonArray) { + JSONObject result = (JSONObject) o; + HashMap map = new HashMap(); + if (result.containsKey("id")) { + map.put("id", result.getString("id")); + } + if (result.containsKey("province")) { + map.put("province", result.getString("province")); + } + if (result.containsKey("tjjProvinceCode")) { + map.put("provinceCode", result.getString("tjjProvinceCode")); + } + if (result.containsKey("city")) { + map.put("city", result.getString("city")); + } + if (result.containsKey("tjjCityCode")) { + map.put("cityCode", result.getString("tjjCityCode")); + } + list.add(map); + } + } + } + basicModel.setResult(list); + mav.setModel(basicModel); + } else { + mav.setModel(BasicModel.buildServerErrorModel().setMsg("·þÎñÉý¼¶ÖÐ...")); + } + return mav; + } + + /** + * Ê¡¼¶ÐÐÕþÇø»®²éѯ½Ó¿Ú + * + * @param model + * @return + */ + public Object listProvinceAction(AddressModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + HttpRequest request = new HttpRequest(); + JSONObject json = null; + try { + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/listProvince", null, "UTF-8"); + } catch (Exception e) { + try { + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/listProvince", null, "UTF-8"); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + if (json != null) { + int code = json.getInt("msgCode"); + String msg = json.getString("msg"); + BasicModel basicModel = new BasicModel(code, msg); + List> list = new ArrayList>(); + if (json.containsKey("result")) { + JSONArray jsonArray = json.getJSONArray("result"); + if (jsonArray != null) { + for (Object o : jsonArray) { + JSONObject result = (JSONObject) o; + HashMap map = new HashMap(); + if (result.containsKey("id")) { + map.put("id", result.getString("id")); + } + if (result.containsKey("province")) { + map.put("province", result.getString("province")); + } + if (result.containsKey("tjjProvinceCode")) { + map.put("provinceCode", result.getString("tjjProvinceCode")); + } + list.add(map); + } + } + } + basicModel.setResult(list); + mav.setModel(basicModel); + } else { + mav.setModel(BasicModel.buildServerErrorModel().setMsg("·þÎñÉý¼¶ÖÐ...")); + } + return mav; + } + + /** + * ÇøÓò¼¶ÐÐÕþÇø»®²éѯ½Ó¿Ú + * + * @param model + * @return + */ + public Object listDistrictAction(AddressModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + HttpRequest request = new HttpRequest(); + JSONObject json = null; + Map params = new HashMap(); + params.put("province", StringUtils.isNotBlank(model.getProvince()) ? model.getProvince() : null); + params.put("city", StringUtils.isNotBlank(model.getCity()) ? model.getCity() : null); + try { + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/listDistrict", params, "UTF-8"); + } catch (Exception e) { + try { + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/listDistrict", params, "UTF-8"); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + if (json != null) { + int code = json.getInt("msgCode"); + String msg = json.getString("msg"); + BasicModel basicModel = new BasicModel(code, msg); + List> list = new ArrayList>(); + if (json.containsKey("result")) { + JSONArray jsonArray = json.getJSONArray("result"); + if (jsonArray != null) { + for (Object o : jsonArray) { + JSONObject result = (JSONObject) o; + HashMap map = new HashMap(); + if (result.containsKey("id")) { + map.put("id", result.getString("id")); + } + if (result.containsKey("province")) { + map.put("province", result.getString("province")); + } + if (result.containsKey("tjjProvinceCode")) { + map.put("provinceCode", result.getString("tjjProvinceCode")); + } + if (result.containsKey("city")) { + map.put("city", result.getString("city")); + } + if (result.containsKey("tjjCityCode")) { + map.put("cityCode", result.getString("tjjCityCode")); + } + if (result.containsKey("district")) { + map.put("district", result.getString("district")); + } + if (result.containsKey("tjjDistrictCode")) { + map.put("districtCode", result.getString("tjjDistrictCode")); + } + list.add(map); + } + } + } + basicModel.setResult(list); + mav.setModel(basicModel); + } else { + mav.setModel(BasicModel.buildServerErrorModel().setMsg("·þÎñÉý¼¶ÖÐ...")); + } + return mav; + } + + public Object listTownshipAction(AddressModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + HttpRequest request = new HttpRequest(); + JSONObject json = null; + Map params = new HashMap(); + params.put("province", StringUtils.isNotBlank(model.getProvince()) ? model.getProvince() : null); + params.put("city", StringUtils.isNotBlank(model.getCity()) ? model.getCity() : null); + params.put("district", StringUtils.isNotBlank(model.getDistrict()) ? model.getDistrict() : null); + try { + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/listTownship", params, "UTF-8"); + } catch (Exception e) { + try { + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/listTownship", params, "UTF-8"); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + if (json != null) { + int code = json.getInt("msgCode"); + String msg = json.getString("msg"); + BasicModel basicModel = new BasicModel(code, msg); + List> list = new ArrayList>(); + if (json.containsKey("result")) { + JSONArray jsonArray = json.getJSONArray("result"); + if (jsonArray != null) { + for (Object o : jsonArray) { + JSONObject result = (JSONObject) o; + HashMap map = new HashMap(); + if (result.containsKey("id")) { + map.put("id", result.getString("id")); + } + if (result.containsKey("province")) { + map.put("province", result.getString("province")); + } + if (result.containsKey("tjjProvinceCode")) { + map.put("provinceCode", result.getString("tjjProvinceCode")); + } + if (result.containsKey("city")) { + map.put("city", result.getString("city")); + } + if (result.containsKey("tjjCityCode")) { + map.put("cityCode", result.getString("tjjCityCode")); + } + if (result.containsKey("district")) { + map.put("district", result.getString("district")); + } + if (result.containsKey("tjjDistrictCode")) { + map.put("districtCode", result.getString("tjjDistrictCode")); + } + if (result.containsKey("street")) { + map.put("street", result.getString("street")); + } + if (result.containsKey("tjjStreetCode")) { + map.put("streetCode", result.getString("tjjStreetCode")); + } + list.add(map); + } + } + } + basicModel.setResult(list); + mav.setModel(basicModel); + } else { + mav.setModel(BasicModel.buildServerErrorModel().setMsg("·þÎñÉý¼¶ÖÐ...")); + } + return mav; + } + + public Object levelAction(AddressModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + HttpRequest request = new HttpRequest(); + JSONObject json = null; + Map params = new HashMap(); + params.put("province", StringUtils.isNotBlank(model.getProvince()) ? model.getProvince() : null); + params.put("city", StringUtils.isNotBlank(model.getCity()) ? model.getCity() : null); + params.put("address", StringUtils.isNotBlank(model.getAddress()) ? model.getAddress() : null); + try { + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/addrLevel", params, "UTF-8"); + } catch (Exception e) { + try { + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/addrLevel", params, "UTF-8"); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + if (json != null) { + int code = json.getInt("msgCode"); + String msg = json.getString("msg"); + BasicModel basicModel = new BasicModel(code, msg); + if (json.containsKey("result")) { + JSONObject result = json.getJSONObject("result"); + basicModel.setResult(result); + } + mav.setModel(basicModel); + } else { + mav.setModel(BasicModel.buildServerErrorModel().setMsg("·þÎñÉý¼¶ÖÐ...")); + } + return mav; + } + public void setDistrictStatService(DistrictStatService districtStatService) { this.districtStatService = districtStatService; } diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/AddressController.java b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/AddressController.java index c50eb7af6..777f96d9a 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/AddressController.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/AddressController.java @@ -619,6 +619,7 @@ public class AddressController { params.setProvince(model.getProvince()); params.setUseMap(model.isUseMap()); params.setDebugName(model.getDebugName()); + params.setPropertyType(model.getPropertyType()); long start = System.currentTimeMillis(); Building building = addressParserService.parser(params); long end = System.currentTimeMillis(); @@ -2134,6 +2135,56 @@ public class AddressController { return mav; } + /** + * Â¥ÅÌÆÀ¼¶ + * + * @param model + * @return + */ + public Object propertyRatingAction(CommunitySummaryRequestDto model) { + + RestfulModelAndView mav = new RestfulModelAndView(); + if (StringUtils.isBlank(model.getAddress()) && StringUtils.isBlank(model.getId())) { + mav.setModel(BasicModel.buildBadRequestModel("Ð¡ÇøID»òµØÖ·²»ÄÜΪ¿Õ")); + return mav; + } + + HttpRequest request = new HttpRequest(); + JSONObject json = null; + try { + Map headers = new HashMap(); + headers.put("Content-Type", "application/json"); + + JSONObject reqBody = new JSONObject(); + reqBody.put("city", model.getCity()); + reqBody.put("address", model.getAddress()); + reqBody.put("id", model.getId()); + String result = request.postWithBody("http://192.168.0.100:32080/FangJiaAddressService/propertyRating", reqBody, headers, "UTF-8"); + if (result != null) { + try { + json = JSONObject.fromObject(result); + } catch (Exception e) { + json = null; + } + } + } catch (Exception e) { + e.printStackTrace(); + } + + if (json != null) { + int code = json.getInt("status"); + String msg = json.getString("msg"); + BasicModel basicModel = new BasicModel(code, msg); + if (json.containsKey("result")) { + basicModel.setResult(json.get("result")); + } + mav.setModel(basicModel); + } else { + mav.setModel(BasicModel.buildServerErrorModel().setMsg("·þÎñÉý¼¶ÖÐ...")); + } + return mav; + } + /** * Â¥ÅÌÆÀ¼¶ * @@ -2196,8 +2247,8 @@ public class AddressController { public Object financialRatingAction(CommunitySummaryRequestDto model) { RestfulModelAndView mav = new RestfulModelAndView(); - if (StringUtils.isBlank(model.getAddress()) || "null".equals(model.getAddress())) { - mav.setModel(BasicModel.buildBadRequestModel("µØÖ·²»ÄÜΪ¿Õ")); + if ((StringUtils.isBlank(model.getAddress()) || "null".equals(model.getAddress())) && StringUtils.isBlank(model.getId())) { + mav.setModel(BasicModel.buildBadRequestModel("µØÖ·ºÍid²»ÄÜͬʱΪ¿Õ")); return mav; } @@ -2209,11 +2260,13 @@ public class AddressController { JSONObject reqBody = new JSONObject(); reqBody.put("city", StringUtils.isNotBlank(model.getCity()) ? model.getCity() : CONFIG.getDefaultCity()); - reqBody.put("address", model.getAddress()); + reqBody.put("address", StringUtils.isNotBlank(model.getAddress()) ? model.getAddress() : ""); + reqBody.put("seaweedId", StringUtils.isNotBlank(model.getId()) ? model.getId() : ""); reqBody.put("area", model.getArea()); reqBody.put("maxFloor", model.getMaxFloor()); reqBody.put("housePurpose", model.getHousePurpose()); reqBody.put("memo", model.getMemo()); + reqBody.put("showOther", false); String result = request.postWithBody("http://192.168.0.100:32080/FangJiaAddressService/financialRating", reqBody, headers, "UTF-8"); if (result != null) { try { @@ -2227,7 +2280,7 @@ public class AddressController { } if (json != null) { - int code = json.getInt("status"); + int code = json.getInt("status") == 0 ? 200 : 0; String msg = json.getString("msg"); BasicModel basicModel = new BasicModel(code, msg); if (json.containsKey("result")) { diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/ComprehensiveQueryController.java b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/ComprehensiveQueryController.java index 9d891b609..1088d4648 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/ComprehensiveQueryController.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/ComprehensiveQueryController.java @@ -42,6 +42,7 @@ import org.slf4j.Logger; import org.sothis.web.mvc.ActionContext; import javax.servlet.http.HttpServletRequest; +import java.math.BigDecimal; import java.text.ParseException; import java.util.*; @@ -78,6 +79,9 @@ public class ComprehensiveQueryController { private static final int DEFAULT_PAGE_SIZE = 20; private static final String[] PROPERTY_SEARCH_API_FIELDS = {"address", "city", "region", "name", "lat2", "lng2", "lat", "lng", "block", "estateType2", "addrAlias"}; + + private static final List GAODE_LEVEL = Arrays.asList("ÐËȤµã", "ÃÅÅÆºÅ", "µ¥ÔªºÅ", "Â¥²ã", "·¿¼ä", "ÃÅÖ·", "×¡Õ¬Çø"); + static final int BAI_DU_GEO = 1;// °Ù¶ÈÏµ×ø±ê static final int GAO_DE_GEO = 2;// ¸ßµÂÏµ×ø±ê @@ -215,10 +219,19 @@ public class ComprehensiveQueryController { mav.setModel(BasicModel.buildBadRequestModel("µØÖ·(address),Ãæ»ý(size)Ϊ±ØÌî×Ö¶Î")); return mav; } + // ²»Ö§³Ö³µÎ»µÈ¹À¼Û + if (model.getAddress().contains("³µÎ»")) { + mav.setModel(BasicModel.buildBadRequestModel("·ÇסլÎÞ·¨¹ÀÖµ")); + return mav; + } String cityStr = model.getCity(); if (StringUtils.isNotBlank(cityStr) && cityStr.matches("\\d+")) { AdministrativeDivision administrativeDivision = administrativeDivisionService.findcityByCode(cityStr); + if(administrativeDivision == null){ + mav.setModel(BasicModel.buildBadRequestModel("³ÇÊдúÂë´íÎó")); + return mav; + } String city = administrativeDivision.getCityShort(); if (StringUtils.isBlank(city)) { mav.setModel(BasicModel.buildBadRequestModel("³ÇÊдúÂë´íÎó")); @@ -232,10 +245,11 @@ public class ComprehensiveQueryController { Map communityAvgPriceParams = new HashMap(); communityAvgPriceParams.put("city", model.getCity()); communityAvgPriceParams.put("address", model.getAddress()); - communityAvgPriceParams.put("category", model.getCategory()); -// communityAvgPriceParams.put("useMap", String.valueOf(model.isUseMap())); + communityAvgPriceParams.put("category", "district"); + communityAvgPriceParams.put("useMap", "true"); communityAvgPriceParams.put("suggestName", String.valueOf(model.getName())); communityAvgPriceParams.put("preciseLevel", "strict"); + communityAvgPriceParams.put("propertyType", model.getPropertyType()); communityAvgPriceParams.put("token", "F54F52381C49BB9EB4A33EB1B65604AE4B71A28AEE53518A94A2F360408B9056D57553931D15CE6DDE765562DAD286BA38E05A4CDAFC51C3D527A4959BF8E75A3B95DB7108FCEA340DDE61925616DB55118E1851E67D83EAD800460D100D6B667A4ED8EE67C8F7FB"); JSONObject matchResponse = null; try { @@ -244,17 +258,47 @@ public class ComprehensiveQueryController { } catch (HttpRequestException e) { } - if (matchResponse == null || !matchResponse.containsKey("result") || !matchResponse.getJSONObject("result").containsKey("id")) { + // È¥µô¾­Î³¶È½âÎö +// if (matchResponse == null || !matchResponse.containsKey("result") || !matchResponse.getJSONObject("result").containsKey("id")) { +// //¼ÓÉϸߵ»ñÈ¡¾­Î³¶È ºÍ ¸ù¾Ý¾­Î³¶È¹ÀÖµ +// Map map = GeoUtils.parserByGaode(model.getCity(), model.getAddress()); +// if (map.containsKey("level") && GAODE_LEVEL.contains(map.get("level")) +// && map.containsKey("lng") && map.containsKey("lat")) { +// String location = map.get("lng") + "," + map.get("lat"); +// JSONObject jsonResult = null; +// Map param = new HashMap(); +// param.put("location", location); +// param.put("area", String.valueOf(model.getSize())); +// try { +// jsonResult = httpRequest.getJsonContent("http://192.168.0.100:30020/avmWeb/avmAnn", param, "UTF-8"); +// if (jsonResult.containsKey("msg") && "³É¹¦".equals(jsonResult.getString("msg"))) { +// HashMap resultMap = new HashMap(); +// resultMap.put("avgPrice", jsonResult.getString("unitPrice")); +// resultMap.put("totalPrice", jsonResult.getString("totalPrice")); +// houseValueInformation.setAddressValue(resultMap); +// mav.setModel(BasicModel.buildOKModel().setResult(houseValueInformation)); +// } else { +// mav.setModel(BasicModel.buildBadRequestModel("¸ÃµØÖ·²»Ö§³Ö¹À¼Û£¡")); +// } +// } catch (HttpRequestException e) { +// throw new RuntimeException(e); +// } +// } else { +// mav.setModel(BasicModel.buildBadRequestModel("¸ÃµØÖ·²»Ö§³Ö¹À¼Û£¡")); +// } +// return mav; +// } + JSONObject result = matchResponse.getJSONObject("result"); + if(!result.containsKey("id")){ mav.setModel(BasicModel.buildBadRequestModel("¸ÃµØÖ·²»Ö§³Ö¹À¼Û£¡")); return mav; } - String id = matchResponse.getJSONObject("result").getString("id"); + String id = matchResponse.getJSONObject("result") .getString("id"); District district = districtService.findById(id); if (district == null) { mav.setModel(BasicModel.buildBadRequestModel("¸ÃµØÖ·²»Ö§³Ö¹À¼Û£¡")); return mav; } - MatchedBuildingDto dto = CommonDtoUtils.transformV(MatchedBuildingDto.class, matchResponse.getJSONObject("result")); DistrictStatBo statBo = districtStatService.findCurrentDistrictStat(new DistrictKey(district)); if (null != statBo) { @@ -277,7 +321,15 @@ public class ComprehensiveQueryController { } } + // ¼Û¸ñϵ÷10% +// if (dto.getAvgPrice() != null) { +// int avgPrice = new BigDecimal(dto.getAvgPrice()).multiply(new BigDecimal(0.9)).intValue(); +// dto.setAvgPrice(avgPrice); +// } + // ·ÇסլÎÞ·¨¹ÀÖµ + // ±£´æÐ¡Çø¾ù¼ÛµÄ·µ»Ø½á¹û + dto.setCredit(null); houseValueInformation.setCommunityAvgPrice(dto); //Ô­·¿ÎݼÛÖµÆÀ¹À @@ -285,12 +337,13 @@ public class ComprehensiveQueryController { PropertyEvaluationModel propertyEvaluationModel = createPropertyEvaluationModelFromHouseInfomationModel(model); boolean villaFlag = DataUtil.isVilla(propertyEvaluationModel.getSize(), propertyEvaluationModel.getName(), propertyEvaluationModel.getHeight(), propertyEvaluationModel.getRoom()); String propertyType = district.getEstateType2(); - if (villaFlag && StringUtils.isNotBlank(propertyType) && !propertyType.equals("±ðÊû")) { - District bieShuDistrict = districtService.findByNameAndAlias(district.getCity(), district.getRegion(), district.getName() + "±ðÊû", "district"); - if (bieShuDistrict != null) { - district = bieShuDistrict; - } - } + // ÒÑÌí¼ÓÎïÒµÀàÐÍ£¬ÏÈ×¢ÊÍ +// if (villaFlag && StringUtils.isNotBlank(propertyType) && !propertyType.equals("±ðÊû")) { +// District bieShuDistrict = districtService.findByNameAndAlias(district.getCity(), district.getRegion(), district.getName() + "±ðÊû", "district"); +// if (bieShuDistrict != null) { +// district = bieShuDistrict; +// } +// } //Ìí¼Ó³ÇÊÐ propertyEvaluationModel.setCity(district.getCity()); propertyEvaluationModel.setDistrict(district.getRegion()); @@ -300,6 +353,13 @@ public class ComprehensiveQueryController { } catch (IllegalAccessException e) { } + // ¼Û¸ñϵ÷10% +// Map addressValue = houseValueInformation.getAddressValue(); +// if (addressValue != null && addressValue.get("totalPrice") != null && addressValue.get("avgPrice") != null) { +// int evaluatePrice = new BigDecimal((Integer) addressValue.get("avgPrice")).multiply(new BigDecimal(0.9)).intValue(); +// addressValue.put("avgPrice", evaluatePrice); +// addressValue.put("totalPrice", new BigDecimal(evaluatePrice * model.getSize()).intValue()); +// } // houseValueInformation.setAddressValue(modelAndView); //·¿Ô´Ñù±¾ @@ -323,7 +383,7 @@ public class ComprehensiveQueryController { } // ´Ë´¦Âý long start = System.currentTimeMillis(); - List collaterals = czbankSampleService.findSample2(querys, sampleQuery.getMax()); + List collaterals = czbankSampleService.findSampleForBse(querys, sampleQuery.getMax()); long end = System.currentTimeMillis(); System.out.println("ÓÃʱ:" + (end - start)); Collateral collateral = collaterals.get(0); @@ -356,6 +416,18 @@ public class ComprehensiveQueryController { // Ô­ÖܱßPOI DistrictFacilitys facilitys = districtFacilitysService.findByDistrict(district); + if (facilitys != null) { + List hospitalList = facilitys.getHospital(); + List hospitals = new ArrayList(); + for (String hospital : hospitalList) { + if (hospital.endsWith("Ò½Ôº")) { + hospitals.add(hospital); + } + } + facilitys.setHospital(hospitals); + } else { + facilitys = new DistrictFacilitys(); + } // ½«ÖܱßPOIÊý¾Ý·Åµ½½á¹û¼¯ houseValueInformation.setSurroundingPoi(facilitys); mav.setModel(BasicModel.buildOKModel().setResult(houseValueInformation)); @@ -679,54 +751,10 @@ public class ComprehensiveQueryController { districtPriceMap.put("city", district.getCity()); districtPriceMap.put("district", district.getRegion()); districtPriceMap.put("name", district.getName()); - districtPriceMap.put("totalPrice", evaluation.getBigTotalPrice()); - if (evaluation.getAvgPrice2b() != null && evaluation.getAvgPrice2b() != 0) { - districtPriceMap.put("avgPrice", evaluation.getAvgPrice2b()); - } else { - districtPriceMap.put("avgPrice", evaluation.getAvgPrice()); - } - - // ¸ù¾Ý³ÇÊÐµÈ ¼¶ÉèÖÃD¼¶¿ÉÐÅ¶È - ApiUserAuthority apiUserAuthority = apiUserAuthorityService - .findByUserId(Long.valueOf(evaluation.getFromUserId())); - if (apiUserAuthority != null && null != apiUserAuthority.getCreditLevelStatus() - && apiUserAuthority.getCreditLevelStatus() == 1) { - double dCredit = 0.61; - if (null != apiUserAuthority.getPriceRatingMap()) { - ServerArea serverArea = serverAreaService.findByDisplay(evaluation.getCity()); - Map rateMap = apiUserAuthority.getPriceRatingMap(); - if (null != rateMap) { - dCredit = rateMap.get(CITYLEVEL_MAP.get(serverArea.getNewCityGrade().toString())); - } - } - Map rMap = getLastEvaluationPrice(district, evaluation, dCredit); - - if (model.getScope() == EVALUATE_SHOW_DETAIL) { - if (null != rMap) { - if (rMap.containsKey("level")) { - districtPriceMap.put("level", rMap.get("level")); - } - if (rMap.containsKey("other_price")) { - districtPriceMap.put("other_price", rMap.get("other_price")); - } - } - } - - Long lastPrice = (Long) rMap.get("lastPrice"); - - if (null != lastPrice) { - districtPriceMap.put("totalPrice", lastPrice); - if (lastPrice > 0 && lastPrice != evaluation.getBigTotalPrice()) { - districtPriceMap.put("avgPrice", (int) (lastPrice / evaluation.getArea())); - } - } else { - mav.setModel(BasicModel.buildOKModel().setMsg("ÔÝʱ²»Ö§³Ö¸ÃÐ¡ÇøµÄ¹À¼Û").markNoData()); - return mav; - } - - } else { - districtPriceMap.put("totalPrice", evaluation.getBigTotalPrice()); - } + // ¹ÀÖµÖÐÒѾ­È¡¹ýÆÀ¹À2B¼Û¸ñ£¬ÇÒ¾­¹ýϵÊýµ÷Õû£¬²»ÄÜÔÚ¸²¸Ç + districtPriceMap.put("avgPrice", evaluation.getAvgPrice()); + Long totalPrice = new BigDecimal((Integer)districtPriceMap.get("avgPrice")).multiply(new BigDecimal(evaluation.getArea())).longValue(); + districtPriceMap.put("totalPrice", totalPrice); if (model.getScope() == EVALUATE_SHOW_DETAIL) { districtPriceMap.put("evaluateWay", evaluation.getEvaluateWay()); @@ -744,7 +772,10 @@ public class ComprehensiveQueryController { } catch (Exception e) { e.printStackTrace(); } - + // ¸ù¾Ýµ¥¼ÛÖØÐ¼ÆËã×Ü¼Û + Integer avgPrice = (Integer) districtPriceMap.get("avgPrice"); + totalPrice = new BigDecimal(avgPrice).multiply(new BigDecimal(evaluation.getArea())).longValue(); + districtPriceMap.put("totalPrice", totalPrice); return mav; } else { evaluationService.remove(evaluation.getId()); @@ -909,9 +940,9 @@ public class ComprehensiveQueryController { otherPriceRets = new HashMap(); } - if (evaluation.getAvgPrice2b()!=null&&evaluation.getAvgPrice2b() > 0){ + if (evaluation.getAvgPrice2b() != null && evaluation.getAvgPrice2b() > 0) { otherPriceRets.put("fjw_price", evaluation.getAvgPrice2b()); - }else { + } else { otherPriceRets.put("fjw_price", evaluation.getAvgPrice()); } Map levelMap = getPriceLevel(otherPriceRets, evaluation.getCredit()); diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/DistrictController.java b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/DistrictController.java index 90bd877e3..28559ace3 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/DistrictController.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/DistrictController.java @@ -10,8 +10,8 @@ import com.fangjia.core.util.DateUtil; import com.fangjia.core.util.HttpRequest; import com.fangjia.dal.mongo.model.*; import com.fangjia.open.dto.addressGovernance.MatchedBuildingDto; -import com.fangjia.open.model.AvgPriceQueryModel; -import com.fangjia.open.model.BasicModel; +import com.fangjia.open.model.*; +import com.fangjia.open.model.weixin.DistrictModel; import com.fangjia.open.util.CommonDtoUtils; import com.fangjia.service.datastore.RegionStatService; import com.fangjia.service.district.DistrictFacilitysService; @@ -20,6 +20,7 @@ import com.fangjia.service.district.RegionStatRentService; import com.fangjia.service.mongo.fangjia.AverageAnalyService; import com.fangjia.service.mongo.fangjia.RegionBlockService; +import com.fangjia.service.mongo.fangjia.SeaweedImagesService; import net.sf.json.JSONArray; import net.sf.json.JSONException; import net.sf.json.JSONObject; @@ -56,8 +57,6 @@ import com.fangjia.open.dto.NewDistrictDto; import com.fangjia.open.interceptors.AuthenticationBean; import com.fangjia.open.interceptors.Authority; import com.fangjia.open.interceptors.Role; -import com.fangjia.open.model.DistrictSearchModel; -import com.fangjia.open.model.RestfulModelAndView; import com.fangjia.service.api.AutoCompleteService; import com.fangjia.service.api.CategoryEnum; import com.fangjia.service.api.KnowbaseService; @@ -77,654 +76,655 @@ import com.fangjia.service.web.MenuService; /** * Ð¡Çø½Ó¿Ú - * + * * @author velna - * */ @Authority(role = Role.USER) public class DistrictController { - private DistrictService districtService; - private MenuService menuService; - private DistrictStatService districtStatService; - private DistrictHouseService districtHouseService; - private AutoCompleteService autoCompleteService; - private KnowbaseService knowbaseService; - private ApiUserService apiUserService; - private ExtractDistrictService extractDistrictService; + private DistrictService districtService; + private MenuService menuService; + private DistrictStatService districtStatService; + private DistrictHouseService districtHouseService; + private AutoCompleteService autoCompleteService; + private KnowbaseService knowbaseService; + private ApiUserService apiUserService; + private ExtractDistrictService extractDistrictService; private RegionBlockService regionBlockService; private RegionStatService regionStatService; private RegionStatRentService regionStatRentService; - private DistrictFacilitysService districtFacilitysService; - + private DistrictFacilitysService districtFacilitysService; + private SeaweedImagesService seaweedImagesService; - public static final String[] COLUMNS = { "id", "name", "estateType", "buildType", "licence", "buildArea", "allArea", - "householdCount", "address", "city", "region", "block", "alias", "lat", "lng", "lat2", "lng2", "finishBuildingDate", - "description", "kind", "carSite", "estateCharge", "cubagePercent", "virescencePercent", "estateCompany", "developer", - "facilities", "traffic", "loopLineInfo", "houseProperty", "buildStructure", "openDate", "sellAddress", "discount", - "fitmentMaterials", "floorInfo", "creationDate", "modificationDate" }; - public Object searchAction(@Param(name = "city") String city, @Param(name = "keyword") String keyword, - @Param(name = "cat") String cat, @Param(name = "limit") int limit) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if (StringUtils.isBlank(city)) { - mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "ËùÔÚ³ÇÊбØÐëÊäÈë")); - } + public static final String[] COLUMNS = {"id", "name", "estateType", "buildType", "licence", "buildArea", "allArea", + "householdCount", "address", "city", "region", "block", "alias", "lat", "lng", "lat2", "lng2", "finishBuildingDate", + "description", "kind", "carSite", "estateCharge", "cubagePercent", "virescencePercent", "estateCompany", "developer", + "facilities", "traffic", "loopLineInfo", "houseProperty", "buildStructure", "openDate", "sellAddress", "discount", + "fitmentMaterials", "floorInfo", "creationDate", "modificationDate"}; - if (StringUtils.isBlank(keyword)) { - mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "¹Ø¼ü×Ö±ØÐëÊäÈë")); - } + public Object searchAction(@Param(name = "city") String city, @Param(name = "keyword") String keyword, + @Param(name = "cat") String cat, @Param(name = "limit") int limit) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isBlank(city)) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "ËùÔÚ³ÇÊбØÐëÊäÈë")); + } - List districts = this.districtService.searchByKeyword(cat, city, keyword, limit); + if (StringUtils.isBlank(keyword)) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "¹Ø¼ü×Ö±ØÐëÊäÈë")); + } - List> result = new ArrayList>(); + List districts = this.districtService.searchByKeyword(cat, city, keyword, limit); - for (District district : districts) { - Map resMap = new HashMap(); - resMap.put("_id", district.getId()); - resMap.put("city", district.getCity()); - resMap.put("region", district.getRegion()); - resMap.put("block", district.getBlock()); - resMap.put("districtName", district.getName()); - resMap.put("address", district.getAddress()); - resMap.put("category", district.getCategory()); - result.add(resMap); - } + List> result = new ArrayList>(); - mav.setModel(result); - return mav; - } + for (District district : districts) { + Map resMap = new HashMap(); + resMap.put("_id", district.getId()); + resMap.put("city", district.getCity()); + resMap.put("region", district.getRegion()); + resMap.put("block", district.getBlock()); + resMap.put("districtName", district.getName()); + resMap.put("address", district.getAddress()); + resMap.put("category", district.getCategory()); + result.add(resMap); + } - public Object fetchByCityAction(@Param(name = "city") String city, @Param(name = "cat") final String cat, - @Param(name = "skip") Integer skip, @Param(name = "limit") Integer limit, - @Param(name = "lastUpdateTime") Long lastUpdateTime) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if (StringUtils.isBlank(city)) { - mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "Ð¡ÇøËùÔÚ³ÇÊбØÐëÊäÈë")); - return mav; - } + mav.setModel(result); + return mav; + } - if (!"district".equals(cat) && !"new_district".equals(cat)) { - mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "Ð¡ÇøÀàÐͱØÐëÊäÈëÕýÈ·")); - return mav; - } + public Object fetchByCityAction(@Param(name = "city") String city, @Param(name = "cat") final String cat, + @Param(name = "skip") Integer skip, @Param(name = "limit") Integer limit, + @Param(name = "lastUpdateTime") Long lastUpdateTime) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isBlank(city)) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "Ð¡ÇøËùÔÚ³ÇÊбØÐëÊäÈë")); + return mav; + } - skip = null == skip ? 0 : skip; - limit = null == limit ? 20 : limit; - System.out.println(new Date().getTime()); + if (!"district".equals(cat) && !"new_district".equals(cat)) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "Ð¡ÇøÀàÐͱØÐëÊäÈëÕýÈ·")); + return mav; + } - if (skip < 0 || skip > 1000000 || limit < 0 || limit > 10000) { - mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "ÇëÇóÊýÁ¿²ÎÊý²»ÕýÈ·")); - return mav; - } + skip = null == skip ? 0 : skip; + limit = null == limit ? 20 : limit; + System.out.println(new Date().getTime()); - List params = new ArrayList(); - params.add(new QueryParam("city", city)); - params.add(new QueryParam("category", cat)); - params.add(new QueryParam("visible", 0)); - if (null != lastUpdateTime) { - params.add(new QueryParam("modificationDate", QueryParam.GREATER_THAN_OPERATOR, new Date(lastUpdateTime))); - } + if (skip < 0 || skip > 1000000 || limit < 0 || limit > 10000) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "ÇëÇóÊýÁ¿²ÎÊý²»ÕýÈ·")); + return mav; + } - Pager pager = new Pager(limit); - pager.setStartRow(skip); - List districtLists = districtService.findDistrictList(pager, params, COLUMNS); + List params = new ArrayList(); + params.add(new QueryParam("city", city)); + params.add(new QueryParam("category", cat)); + params.add(new QueryParam("visible", 0)); + if (null != lastUpdateTime) { + params.add(new QueryParam("modificationDate", QueryParam.GREATER_THAN_OPERATOR, new Date(lastUpdateTime))); + } - List districtDtos = org.sothis.core.util.CollectionUtils.collect(districtLists, - new Closure() { - public DistrictDto execute(District obj) { - DistrictBo bo = new DistrictBo(obj); - DistrictDto ret = null; - if ("new_district".equals(cat)) { - ret = new NewDistrictDto(bo, true); - } else { - ret = new DistrictDto(bo, true); - } - ret.setAlias(obj.getAlias()); - return ret; - } - }); + Pager pager = new Pager(limit); + pager.setStartRow(skip); + List districtLists = districtService.findDistrictList(pager, params, COLUMNS); - mav.setModel(districtDtos); - return mav; - } + List districtDtos = org.sothis.core.util.CollectionUtils.collect(districtLists, + new Closure() { + public DistrictDto execute(District obj) { + DistrictBo bo = new DistrictBo(obj); + DistrictDto ret = null; + if ("new_district".equals(cat)) { + ret = new NewDistrictDto(bo, true); + } else { + ret = new DistrictDto(bo, true); + } + ret.setAlias(obj.getAlias()); + return ret; + } + }); - /** - * ¸ù¾Ý³ÇÊк͹ؼü´ÊÈ¡Ð¡Çø - * - * @param city - * @param keyword - * @param request - * @return - */ - public Object fetchByKeywordAction(@Param(name = "city") String city, @Param(name = "keyword") String keyword, - HttpServletRequest request) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if (StringUtils.isBlank(city)) { - mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "Ð¡ÇøËùÔÚ³ÇÊбØÐëÊäÈë")); - return mav; - } - if (StringUtils.isBlank(keyword)) { - mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "¹Ø¼ü´Ê±ØÐëÊäÈë")); - return mav; - } - List districtNames = autoCompleteService.suggestDistrict(keyword, city, 10); - if (CollectionUtils.isNotEmpty(districtNames)) { - DistrictDto districtDto = null; - for (String districtName : districtNames) { - DistrictQueryBean queryBean = new DistrictQueryBean(); - queryBean.setCity(city); - queryBean.setCategory("district"); - queryBean.setName(districtName); - List districtBos = this.districtService.findByCompactMode(queryBean.getQueryParams(), null, 0, 20); - if (CollectionUtils.isNotEmpty(districtBos)) { - DistrictBo bo = districtBos.get(0); - if ("district".equals(bo.getCategory())) { - districtDto = new DistrictDto(bo, isSupportLatLng(request)); - } else { - districtDto = new NewDistrictDto(bo, isSupportLatLng(request)); - } - DistrictHouse dh = this.districtHouseService.findDistrictHouseByDistrictKey(bo.getDistrictKey()); - if (dh != null) { - districtDto.setSellCount(dh.getSellCount()); - districtDto.setRentCount(dh.getRentCount()); - } - break; - } - } - if (null != districtDto) { - mav.setModel(districtDto); - } - } - return mav; - } + mav.setModel(districtDtos); + return mav; + } - /** - * ¸ù¾Ý¹Ø¼ü´ÊÈ¡Ð¡Çø - * - * @param city - * @param keyword - * @param request - * @return - */ - public Object fetchSimpleAction(@Param(name = "city") String city, @Param(name = "keyword") String keyword, - HttpServletRequest request) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if (StringUtils.isBlank(keyword)) { - mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "¹Ø¼ü´Ê±ØÐëÊäÈë")); - return mav; - } + /** + * ¸ù¾Ý³ÇÊк͹ؼü´ÊÈ¡Ð¡Çø + * + * @param city + * @param keyword + * @param request + * @return + */ + public Object fetchByKeywordAction(@Param(name = "city") String city, @Param(name = "keyword") String keyword, + HttpServletRequest request) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isBlank(city)) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "Ð¡ÇøËùÔÚ³ÇÊбØÐëÊäÈë")); + return mav; + } + if (StringUtils.isBlank(keyword)) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "¹Ø¼ü´Ê±ØÐëÊäÈë")); + return mav; + } + List districtNames = autoCompleteService.suggestDistrict(keyword, city, 10); + if (CollectionUtils.isNotEmpty(districtNames)) { + DistrictDto districtDto = null; + for (String districtName : districtNames) { + DistrictQueryBean queryBean = new DistrictQueryBean(); + queryBean.setCity(city); + queryBean.setCategory("district"); + queryBean.setName(districtName); + List districtBos = this.districtService.findByCompactMode(queryBean.getQueryParams(), null, 0, 20); + if (CollectionUtils.isNotEmpty(districtBos)) { + DistrictBo bo = districtBos.get(0); + if ("district".equals(bo.getCategory())) { + districtDto = new DistrictDto(bo, isSupportLatLng(request)); + } else { + districtDto = new NewDistrictDto(bo, isSupportLatLng(request)); + } + DistrictHouse dh = this.districtHouseService.findDistrictHouseByDistrictKey(bo.getDistrictKey()); + if (dh != null) { + districtDto.setSellCount(dh.getSellCount()); + districtDto.setRentCount(dh.getRentCount()); + } + break; + } + } + if (null != districtDto) { + mav.setModel(districtDto); + } + } + return mav; + } - ServerArea serverArea = ServerAreaData.getServerAreaByDisplayDefaultNull(city); - if (serverArea == null) { - serverArea = ServerAreaData.getServerAreaBySpellDefaultNull(city); - if (null == serverArea) { - serverArea = ServerAreaData.valueOfName(city); - } - } + /** + * ¸ù¾Ý¹Ø¼ü´ÊÈ¡Ð¡Çø + * + * @param city + * @param keyword + * @param request + * @return + */ + public Object fetchSimpleAction(@Param(name = "city") String city, @Param(name = "keyword") String keyword, + HttpServletRequest request) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isBlank(keyword)) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "¹Ø¼ü´Ê±ØÐëÊäÈë")); + return mav; + } - List districtNames = autoCompleteService.suggestDistrict(keyword, serverArea.getDisplay(), 10); - if (CollectionUtils.isNotEmpty(districtNames)) { - List> ret = new ArrayList>(10); - for (String districtName : districtNames) { - DistrictQueryBean queryBean = new DistrictQueryBean(); - queryBean.setCity(serverArea.getDisplay()); - queryBean.setCategory("district"); - queryBean.setName(districtName); - List districtBos = this.districtService.findByCompactMode(queryBean.getQueryParams(), null, 0, 20); - if (CollectionUtils.isNotEmpty(districtBos)) { - DistrictKey key = districtBos.get(0).getDistrictKey(); - Map info = new HashMap(3); - info.put("city", serverArea.getDisplay()); - info.put("region", key.getRegion()); - info.put("name", key.getName()); - ret.add(info); - } - } - if (ret.size() > 0) { - mav.setModel(ret); - } - } - return mav; - } + ServerArea serverArea = ServerAreaData.getServerAreaByDisplayDefaultNull(city); + if (serverArea == null) { + serverArea = ServerAreaData.getServerAreaBySpellDefaultNull(city); + if (null == serverArea) { + serverArea = ServerAreaData.valueOfName(city); + } + } - /** - * Ð¡ÇøËÑË÷ - * - * @return - */ - public Object listAction(DistrictSearchModel model, HttpServletRequest request) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if (StringUtils.isBlank(model.getCity())) { - mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "Ð¡ÇøËùÔÚ³ÇÊбØÐëÊäÈë")); - return mav; - } - Pager pager = new Pager(); - int maxPageSize = OpenConfig.getConfig().getSearchListMaxPageSize(); - int maxPageIndex = OpenConfig.getConfig().getSearchListMaxPageNo(); - if (model.getPageSize() != null && model.getPageSize() > 0) { - pager.setPageSize(model.getPageSize() > maxPageSize ? maxPageSize : model.getPageSize()); - } else { - pager.setPageSize(20); - } - if (model.getPageIndex() != null && model.getPageIndex() > 1) { - int pageIndex = model.getPageIndex() > maxPageIndex ? maxPageIndex : model.getPageIndex(); - int startRow = (pageIndex - 1) * pager.getPageSize(); - pager.setStartRow(startRow); - } - // ÊÇ·ñÊäÈë°ë¾¶²éѯ£¬ÆäËûÇé¿öÖ±½Ómoedel²éѯ¼´¿É - if (isRadiusSearch(model)) { - Long lng = model.getLng(); - Long lat = model.getLat(); + List districtNames = autoCompleteService.suggestDistrict(keyword, serverArea.getDisplay(), 10); + if (CollectionUtils.isNotEmpty(districtNames)) { + List> ret = new ArrayList>(10); + for (String districtName : districtNames) { + DistrictQueryBean queryBean = new DistrictQueryBean(); + queryBean.setCity(serverArea.getDisplay()); + queryBean.setCategory("district"); + queryBean.setName(districtName); + List districtBos = this.districtService.findByCompactMode(queryBean.getQueryParams(), null, 0, 20); + if (CollectionUtils.isNotEmpty(districtBos)) { + DistrictKey key = districtBos.get(0).getDistrictKey(); + Map info = new HashMap(3); + info.put("city", serverArea.getDisplay()); + info.put("region", key.getRegion()); + info.put("name", key.getName()); + ret.add(info); + } + } + if (ret.size() > 0) { + mav.setModel(ret); + } + } + return mav; + } - model.setLng(lng); - model.setLat(lat); + /** + * Ð¡ÇøËÑË÷ + * + * @return + */ + public Object listAction(DistrictSearchModel model, HttpServletRequest request) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isBlank(model.getCity())) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "Ð¡ÇøËùÔÚ³ÇÊбØÐëÊäÈë")); + return mav; + } + Pager pager = new Pager(); + int maxPageSize = OpenConfig.getConfig().getSearchListMaxPageSize(); + int maxPageIndex = OpenConfig.getConfig().getSearchListMaxPageNo(); + if (model.getPageSize() != null && model.getPageSize() > 0) { + pager.setPageSize(model.getPageSize() > maxPageSize ? maxPageSize : model.getPageSize()); + } else { + pager.setPageSize(20); + } + if (model.getPageIndex() != null && model.getPageIndex() > 1) { + int pageIndex = model.getPageIndex() > maxPageIndex ? maxPageIndex : model.getPageIndex(); + int startRow = (pageIndex - 1) * pager.getPageSize(); + pager.setStartRow(startRow); + } + // ÊÇ·ñÊäÈë°ë¾¶²éѯ£¬ÆäËûÇé¿öÖ±½Ómoedel²éѯ¼´¿É + if (isRadiusSearch(model)) { + Long lng = model.getLng(); + Long lat = model.getLat(); - Long lngMin = (lng - (model.getRadius() * 100000L)); - model.setLngMin(lngMin); - Long lngMax = (lng + (model.getRadius() * 100000L)); - model.setLngMax(lngMax); - Long latMin = (lat - (model.getRadius() * 100000L)); - model.setLatMin(latMin); - Long latMax = (lat + (model.getRadius() * 100000L)); - model.setLatMax(latMax); + model.setLng(lng); + model.setLat(lat); - model.setRegion(null); - model.setName(null); - } else if (model.getLatA() != null && model.getLatB() != null && model.getLngA() != null && model.getLngB() != null) { - Long lngMin = Math.min(model.getLngA(), model.getLngB()); - Long lngMax = Math.max(model.getLngA(), model.getLngB()); - Long latMin = Math.min(model.getLatA(), model.getLatB()); - Long latMax = Math.max(model.getLatA(), model.getLatB()); + Long lngMin = (lng - (model.getRadius() * 100000L)); + model.setLngMin(lngMin); + Long lngMax = (lng + (model.getRadius() * 100000L)); + model.setLngMax(lngMax); + Long latMin = (lat - (model.getRadius() * 100000L)); + model.setLatMin(latMin); + Long latMax = (lat + (model.getRadius() * 100000L)); + model.setLatMax(latMax); - model.setLngMin(lngMin); - model.setLngMax(lngMax); - model.setLatMin(latMin); - model.setLatMax(latMax); - } - Menu menu = menuService.menuMaker(FangjiaServerAreaContextHolder.getServerAreaDefault(), MenuCategoryEnum.xiaoqu, - getCurrentParams(), 1); - FacetQueryResult result; - if (StringUtils.isBlank(model.getKeyword())) { - result = districtService.findByQueryBeanWithFacet(menu, pager, (DistrictQueryBean) model.getQueryBean(), "bscore", - false, false); - } else { - result = districtService.findByQueryBeanWithFacet(menu, pager, (DistrictQueryBean) model.getQueryBean(), null, false, - false); - } - Map statMap = districtStatService.findDistrictStat(districtService.getDistrictKeys(result)); - FacetQueryResult districtList = new FacetQueryResult(result.size()); - for (District district : result) { - DistrictBo districtBo = new DistrictBo(district); - districtBo.setStat(statMap.get(district.getDistrictKey())); - districtList.add(districtBo); - } - districtList.setNumberFound(result.getNumberFound()); + model.setRegion(null); + model.setName(null); + } else if (model.getLatA() != null && model.getLatB() != null && model.getLngA() != null && model.getLngB() != null) { + Long lngMin = Math.min(model.getLngA(), model.getLngB()); + Long lngMax = Math.max(model.getLngA(), model.getLngB()); + Long latMin = Math.min(model.getLatA(), model.getLatB()); + Long latMax = Math.max(model.getLatA(), model.getLatB()); - FacetQueryResult districtDtos = new FacetQueryResult(); - for (DistrictBo bo : districtList) { - DistrictDto districtDto = null; - if ("district".equals(bo.getCategory())) { - districtDto = new DistrictDto(bo, isSupportLatLng(request)); - } else { - districtDto = new NewDistrictDto(bo, isSupportLatLng(request)); - } - if (StringUtils.isNotBlank(model.getHouseCountType())) { - DistrictHouse dh = this.districtHouseService.findDistrictHouseByDistrictKey(bo.getDistrictKey()); - if (dh != null) { - if (CategoryEnum.sell.name().equals(model.getHouseCountType())) { - districtDto.setSellCount(dh.getSellCount()); - } else if (CategoryEnum.rent.name().equals(model.getHouseCountType())) { - districtDto.setRentCount(dh.getRentCount()); - } - } - } - // Èô´æÔÚÍ⾰ͼÔòÖ»¿¼ÂÇÍ⾰ͼ - List outPics = bo.getOutPics(); - if (CollectionUtils.isNotEmpty(outPics)) { - // ±ê־ͼȡÖмäÒ»ÕÅ - districtDto.setPic(outPics.get(outPics.size() / 2)); - if (outPics.size() <= 5) { - districtDto.setPics(outPics); - } else { - districtDto.setPics(outPics.subList(0, 5)); - } - // districtDto.setPic(model.getPicUrl() + - // DataUtil.encodePicUrl(districtDto.getPic(), "s", - // "district")); - // List picsNew = new ArrayList(); - // List pics = districtDto.getPics(); - // for (String url : pics) { - // url = model.getPicUrl() + DataUtil.encodePicUrl(url, "s", - // "district"); - // picsNew.add(url); - // } - // districtDto.setPics(picsNew); - } - districtDtos.add(districtDto); - } - districtDtos.setNumberFound(districtList.getNumberFound()); - mav.setModel(new DistrictsDto(districtDtos, ((Number) districtDtos.getNumberFound()).longValue())); - return mav; - } + model.setLngMin(lngMin); + model.setLngMax(lngMax); + model.setLatMin(latMin); + model.setLatMax(latMax); + } + Menu menu = menuService.menuMaker(FangjiaServerAreaContextHolder.getServerAreaDefault(), MenuCategoryEnum.xiaoqu, + getCurrentParams(), 1); + FacetQueryResult result; + if (StringUtils.isBlank(model.getKeyword())) { + result = districtService.findByQueryBeanWithFacet(menu, pager, (DistrictQueryBean) model.getQueryBean(), "bscore", + false, false); + } else { + result = districtService.findByQueryBeanWithFacet(menu, pager, (DistrictQueryBean) model.getQueryBean(), null, false, + false); + } + Map statMap = districtStatService.findDistrictStat(districtService.getDistrictKeys(result)); + FacetQueryResult districtList = new FacetQueryResult(result.size()); + for (District district : result) { + DistrictBo districtBo = new DistrictBo(district); + districtBo.setStat(statMap.get(district.getDistrictKey())); + districtList.add(districtBo); + } + districtList.setNumberFound(result.getNumberFound()); - private Map getCurrentParams() { - Map paramMap = ActionContext.getContext().getParameters(); - Map ret = new HashMap(); + FacetQueryResult districtDtos = new FacetQueryResult(); + for (DistrictBo bo : districtList) { + DistrictDto districtDto = null; + if ("district".equals(bo.getCategory())) { + districtDto = new DistrictDto(bo, isSupportLatLng(request)); + } else { + districtDto = new NewDistrictDto(bo, isSupportLatLng(request)); + } + if (StringUtils.isNotBlank(model.getHouseCountType())) { + DistrictHouse dh = this.districtHouseService.findDistrictHouseByDistrictKey(bo.getDistrictKey()); + if (dh != null) { + if (CategoryEnum.sell.name().equals(model.getHouseCountType())) { + districtDto.setSellCount(dh.getSellCount()); + } else if (CategoryEnum.rent.name().equals(model.getHouseCountType())) { + districtDto.setRentCount(dh.getRentCount()); + } + } + } + // Èô´æÔÚÍ⾰ͼÔòÖ»¿¼ÂÇÍ⾰ͼ + List outPics = bo.getOutPics(); + if (CollectionUtils.isNotEmpty(outPics)) { + // ±ê־ͼȡÖмäÒ»ÕÅ + districtDto.setPic(outPics.get(outPics.size() / 2)); + if (outPics.size() <= 5) { + districtDto.setPics(outPics); + } else { + districtDto.setPics(outPics.subList(0, 5)); + } + // districtDto.setPic(model.getPicUrl() + + // DataUtil.encodePicUrl(districtDto.getPic(), "s", + // "district")); + // List picsNew = new ArrayList(); + // List pics = districtDto.getPics(); + // for (String url : pics) { + // url = model.getPicUrl() + DataUtil.encodePicUrl(url, "s", + // "district"); + // picsNew.add(url); + // } + // districtDto.setPics(picsNew); + } + districtDtos.add(districtDto); + } + districtDtos.setNumberFound(districtList.getNumberFound()); + mav.setModel(new DistrictsDto(districtDtos, ((Number) districtDtos.getNumberFound()).longValue())); + return mav; + } - for (String key : paramMap.keySet()) { - Object[] obj = paramMap.get(key); - if (obj != null && obj.length > 0) { - ret.put(key, obj[0].toString()); - } - } - return ret; - } + private Map getCurrentParams() { + Map paramMap = ActionContext.getContext().getParameters(); + Map ret = new HashMap(); - /** - * ÊÇ·ñ¿ÉÒÔÌṩ¾­Î³¶È - * - * @param request - * @return - */ - private boolean isSupportLatLng(HttpServletRequest request) { - AuthenticationBean bean = (AuthenticationBean) request.getAttribute(AuthenticationBean.ATTR_AUTHENTICATION_BEAN); - if (null != bean) { - if (null != bean.auth) { - return bean.auth.isSupportLatLng(); - } - } - return false; - } + for (String key : paramMap.keySet()) { + Object[] obj = paramMap.get(key); + if (obj != null && obj.length > 0) { + ret.put(key, obj[0].toString()); + } + } + return ret; + } - /** - * Ð¡ÇøÏêÇé - * - * @return - */ - public Object showAction(DistrictSearchModel model, @Param(name = "city") String city, @Param(name = "region") String region, - @Param(name = "name") String name, HttpServletRequest request) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if (StringUtils.isBlank(name) || StringUtils.isBlank(city) || StringUtils.isBlank(region)) { - mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "Ð¡ÇøËùÔÚ³ÇÊÐ,Ð¡ÇøÃû,ËùÔÚÇøÓò±Ø±ØÐëÊäÈë")); - return mav; - } else { - DistrictBo districtBo = districtService.findByFullMode(new DistrictKey(city, region, name)); - if (null == districtBo) { - mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "Ð¡ÇøÊý¾Ý²»´æÔÚ£¬Çë¼ì²é²éѯÌõ¼þ")); - return mav; - } - districtBo.setStat(this.districtStatService.findDistrictStat(districtBo.getDistrictKey())); - // È¥³ýÐ¡ÇøÃèÊöÖеÄhtml±êÇ© - districtBo.setDescription(DataUtil.removeSpecialString(districtBo.getDescription())); - DistrictHouse dh = this.districtHouseService.findDistrictHouseByDistrictKey(new DistrictKey(city, region, name)); - DistrictDto districtDto = new DistrictDto(districtBo, isSupportLatLng(request)); - if (dh != null) { - districtDto.setSellCount(dh.getSellCount()); - districtDto.setRentCount(dh.getRentCount()); - } - // Èô´æÔÚÍ⾰ͼÔòÖ»¿¼ÂÇÍ⾰ͼ£¬ÈôÎÞÍ⾰ͼÔòÎÞͼƬ£¬È¡Ç°5ÕÅ - List outPics = districtBo.getOutPics(); - if (CollectionUtils.isNotEmpty(outPics)) { - // ±ê־ͼȡÖмäÒ»ÕÅ - districtDto.setPic(outPics.get(outPics.size() / 2)); - if (outPics.size() <= 5) { - districtDto.setPics(outPics); - } else { - districtDto.setPics(outPics.subList(0, 5)); - } - // districtDto.setPic(model.getPicUrl() + - // DataUtil.encodePicUrl(districtDto.getPic(), "o", - // "district")); - // List picsNew = new ArrayList(); - // List pics = districtDto.getPics(); - // for (String url : pics) { - // url = model.getPicUrl() + DataUtil.encodePicUrl(url, "o", - // "district"); - // picsNew.add(url); - // } - // districtDto.setPics(picsNew); - } - districtDto.setUrl("http://" + ServerAreaData.getServerAreaByDisplay(city).getSpell() + ".fangjia.com/xiaoqu-xinxi-" - + name + "-" + region); - mav.setModel(districtDto); - return mav; - } - } + /** + * ÊÇ·ñ¿ÉÒÔÌṩ¾­Î³¶È + * + * @param request + * @return + */ + private boolean isSupportLatLng(HttpServletRequest request) { + AuthenticationBean bean = (AuthenticationBean) request.getAttribute(AuthenticationBean.ATTR_AUTHENTICATION_BEAN); + if (null != bean) { + if (null != bean.auth) { + return bean.auth.isSupportLatLng(); + } + } + return false; + } - /** - * ÖÇÄܽâÎöÐ¡ÇøÏêÇé - * - * @return - */ - public Object showDetailAction(DistrictSearchModel model, @Param(name = "city") String city, - @Param(name = "region") String region, @Param(name = "name") String name, HttpServletRequest request) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if (StringUtils.isBlank(name) || StringUtils.isBlank(city) || StringUtils.isBlank(region)) { - mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "Ð¡ÇøËùÔÚ³ÇÊÐ,Ð¡ÇøÃû,ËùÔÚÇøÓò±Ø±ØÐëÊäÈë")); - return mav; - } - city = knowbaseService.matchingCityDefaultNull(city); - region = knowbaseService.matchingRegionDefaultNull(region, city); - if (null == city || null == region) { - mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "Ð¡ÇøËùÔÚ³ÇÊлòËùÔÚÇøÓò²»´æÔÚ")); - return mav; - } - District tempDistrict = null; - Map konwbase = knowbaseService.parseWord(name); - List> districts = (null != konwbase && null != konwbase.get("district_name")) ? (List>) konwbase - .get("district_name") : Collections.EMPTY_LIST; - if (CollectionUtils.isNotEmpty(districts)) { - for (Map district : districts) { - Map extra_data = (Map) district.get("extra_data"); - if (MapUtils.isNotEmpty(extra_data)) { - region = (String) extra_data.get("region"); - name = (String) district.get("value"); - String tempCity = (String) extra_data.get("city"); - if (null == city && tempCity != null) { - city = tempCity; - } else if (tempCity == null || (tempCity != null && !tempCity.equals(city))) { - continue; - } - District d = districtService.findDistrict(new DistrictKey(city, region, name), false); - if (null == d) { - continue; - } - tempDistrict = d; - break; - } - } - } - if (null == tempDistrict) { - mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "Ð¡ÇøÊý¾Ý²»´æÔÚ£¬Çë¼ì²é²éѯÌõ¼þ")); - return mav; - } - DistrictBo districtBo = districtService.findByFullMode(new DistrictKey(tempDistrict.getCity(), tempDistrict.getRegion(), - tempDistrict.getName())); - if (null == districtBo) { - mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "Ð¡ÇøÊý¾Ý²»´æÔÚ£¬Çë¼ì²é²éѯÌõ¼þ")); - return mav; - } - districtBo.setStat(this.districtStatService.findDistrictStat(districtBo.getDistrictKey())); - // È¥³ýÐ¡ÇøÃèÊöÖеÄhtml±êÇ© - districtBo.setDescription(DataUtil.removeSpecialString(districtBo.getDescription())); - DistrictHouse dh = this.districtHouseService.findDistrictHouseByDistrictKey(new DistrictKey(city, region, name)); - DistrictDto districtDto = new DistrictDto(districtBo, isSupportLatLng(request)); - if (dh != null) { - districtDto.setSellCount(dh.getSellCount()); - districtDto.setRentCount(dh.getRentCount()); - } + /** + * Ð¡ÇøÏêÇé + * + * @return + */ + public Object showAction(DistrictSearchModel model, @Param(name = "city") String city, @Param(name = "region") String region, + @Param(name = "name") String name, HttpServletRequest request) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isBlank(name) || StringUtils.isBlank(city) || StringUtils.isBlank(region)) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "Ð¡ÇøËùÔÚ³ÇÊÐ,Ð¡ÇøÃû,ËùÔÚÇøÓò±Ø±ØÐëÊäÈë")); + return mav; + } else { + DistrictBo districtBo = districtService.findByFullMode(new DistrictKey(city, region, name)); + if (null == districtBo) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "Ð¡ÇøÊý¾Ý²»´æÔÚ£¬Çë¼ì²é²éѯÌõ¼þ")); + return mav; + } + districtBo.setStat(this.districtStatService.findDistrictStat(districtBo.getDistrictKey())); + // È¥³ýÐ¡ÇøÃèÊöÖеÄhtml±êÇ© + districtBo.setDescription(DataUtil.removeSpecialString(districtBo.getDescription())); + DistrictHouse dh = this.districtHouseService.findDistrictHouseByDistrictKey(new DistrictKey(city, region, name)); + DistrictDto districtDto = new DistrictDto(districtBo, isSupportLatLng(request)); + if (dh != null) { + districtDto.setSellCount(dh.getSellCount()); + districtDto.setRentCount(dh.getRentCount()); + } + // Èô´æÔÚÍ⾰ͼÔòÖ»¿¼ÂÇÍ⾰ͼ£¬ÈôÎÞÍ⾰ͼÔòÎÞͼƬ£¬È¡Ç°5ÕÅ + List outPics = districtBo.getOutPics(); + if (CollectionUtils.isNotEmpty(outPics)) { + // ±ê־ͼȡÖмäÒ»ÕÅ + districtDto.setPic(outPics.get(outPics.size() / 2)); + if (outPics.size() <= 5) { + districtDto.setPics(outPics); + } else { + districtDto.setPics(outPics.subList(0, 5)); + } + // districtDto.setPic(model.getPicUrl() + + // DataUtil.encodePicUrl(districtDto.getPic(), "o", + // "district")); + // List picsNew = new ArrayList(); + // List pics = districtDto.getPics(); + // for (String url : pics) { + // url = model.getPicUrl() + DataUtil.encodePicUrl(url, "o", + // "district"); + // picsNew.add(url); + // } + // districtDto.setPics(picsNew); + } + districtDto.setUrl("http://" + ServerAreaData.getServerAreaByDisplay(city).getSpell() + ".fangjia.com/xiaoqu-xinxi-" + + name + "-" + region); + mav.setModel(districtDto); + return mav; + } + } - // Èô´æÔÚÍ⾰ͼÔòÖ»¿¼ÂÇÍ⾰ͼ£¬ÈôÎÞÍ⾰ͼÔòÎÞͼƬ£¬È¡Ç°5ÕÅ - List outPics = districtBo.getOutPics(); - if (CollectionUtils.isNotEmpty(outPics)) { - // ±ê־ͼȡÖмäÒ»ÕÅ - districtDto.setPic(outPics.get(outPics.size() / 2)); - if (outPics.size() <= 5) { - districtDto.setPics(outPics); - } else { - districtDto.setPics(outPics.subList(0, 5)); - } - // districtDto.setPic(model.getPicUrl() + - // DataUtil.encodePicUrl(districtDto.getPic(), "o", "district")); - // List picsNew = new ArrayList(); - // List pics = districtDto.getPics(); - // for (String url : pics) { - // url = model.getPicUrl() + DataUtil.encodePicUrl(url, "o", - // "district"); - // picsNew.add(url); - // } - // districtDto.setPics(picsNew); - } - districtDto.setUrl("http://" + ServerAreaData.getServerAreaByDisplay(city).getSpell() + ".fangjia.com/xiaoqu-xinxi-" - + name + "-" + region); - mav.setModel(districtDto); - return mav; - } + /** + * ÖÇÄܽâÎöÐ¡ÇøÏêÇé + * + * @return + */ + public Object showDetailAction(DistrictSearchModel model, @Param(name = "city") String city, + @Param(name = "region") String region, @Param(name = "name") String name, HttpServletRequest request) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isBlank(name) || StringUtils.isBlank(city) || StringUtils.isBlank(region)) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "Ð¡ÇøËùÔÚ³ÇÊÐ,Ð¡ÇøÃû,ËùÔÚÇøÓò±Ø±ØÐëÊäÈë")); + return mav; + } + city = knowbaseService.matchingCityDefaultNull(city); + region = knowbaseService.matchingRegionDefaultNull(region, city); + if (null == city || null == region) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "Ð¡ÇøËùÔÚ³ÇÊлòËùÔÚÇøÓò²»´æÔÚ")); + return mav; + } + District tempDistrict = null; + Map konwbase = knowbaseService.parseWord(name); + List> districts = (null != konwbase && null != konwbase.get("district_name")) ? (List>) konwbase + .get("district_name") : Collections.EMPTY_LIST; + if (CollectionUtils.isNotEmpty(districts)) { + for (Map district : districts) { + Map extra_data = (Map) district.get("extra_data"); + if (MapUtils.isNotEmpty(extra_data)) { + region = (String) extra_data.get("region"); + name = (String) district.get("value"); + String tempCity = (String) extra_data.get("city"); + if (null == city && tempCity != null) { + city = tempCity; + } else if (tempCity == null || (tempCity != null && !tempCity.equals(city))) { + continue; + } + District d = districtService.findDistrict(new DistrictKey(city, region, name), false); + if (null == d) { + continue; + } + tempDistrict = d; + break; + } + } + } + if (null == tempDistrict) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "Ð¡ÇøÊý¾Ý²»´æÔÚ£¬Çë¼ì²é²éѯÌõ¼þ")); + return mav; + } + DistrictBo districtBo = districtService.findByFullMode(new DistrictKey(tempDistrict.getCity(), tempDistrict.getRegion(), + tempDistrict.getName())); + if (null == districtBo) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "Ð¡ÇøÊý¾Ý²»´æÔÚ£¬Çë¼ì²é²éѯÌõ¼þ")); + return mav; + } + districtBo.setStat(this.districtStatService.findDistrictStat(districtBo.getDistrictKey())); + // È¥³ýÐ¡ÇøÃèÊöÖеÄhtml±êÇ© + districtBo.setDescription(DataUtil.removeSpecialString(districtBo.getDescription())); + DistrictHouse dh = this.districtHouseService.findDistrictHouseByDistrictKey(new DistrictKey(city, region, name)); + DistrictDto districtDto = new DistrictDto(districtBo, isSupportLatLng(request)); + if (dh != null) { + districtDto.setSellCount(dh.getSellCount()); + districtDto.setRentCount(dh.getRentCount()); + } - public Object showListAction(DistrictSearchModel model, HttpServletRequest request) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if (StringUtils.isBlank(model.getCity())) { - mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "Ð¡ÇøËùÔÚ³ÇÊбØÐëÊäÈë")); - return mav; - } - Pager pager = new Pager(); - int maxPageSize = OpenConfig.getConfig().getSearchListMaxPageSize(); - int maxPageIndex = OpenConfig.getConfig().getSearchListMaxPageNo(); - if (model.getPageSize() != null && model.getPageSize() > 0) { - pager.setPageSize(model.getPageSize() > maxPageSize ? maxPageSize : model.getPageSize()); - } else { - pager.setPageSize(20); - } - if (model.getPageIndex() != null && model.getPageIndex() > 1) { - int pageIndex = model.getPageIndex() > maxPageIndex ? maxPageIndex : model.getPageIndex(); - int startRow = (pageIndex - 1) * pager.getPageSize(); - pager.setStartRow(startRow); - } - FacetQueryResult result; - if (StringUtils.isBlank(model.getKeyword())) { - result = districtService.findByQueryBeanWithoutSrQuery(pager, (DistrictQueryBean) model.getQueryBean(), true); - } else { - result = districtService.findByQueryBeanWithoutSrQuery(pager, (DistrictQueryBean) model.getQueryBean(), true); - } - Map statMap = districtStatService.findDistrictStat(districtService.getDistrictKeys(result)); - FacetQueryResult districtList = new FacetQueryResult(result.size()); - for (District district : result) { - DistrictBo districtBo = new DistrictBo(district); - districtBo.setStat(statMap.get(district.getDistrictKey())); - districtList.add(districtBo); - } - districtList.setNumberFound(result.getNumberFound()); + // Èô´æÔÚÍ⾰ͼÔòÖ»¿¼ÂÇÍ⾰ͼ£¬ÈôÎÞÍ⾰ͼÔòÎÞͼƬ£¬È¡Ç°5ÕÅ + List outPics = districtBo.getOutPics(); + if (CollectionUtils.isNotEmpty(outPics)) { + // ±ê־ͼȡÖмäÒ»ÕÅ + districtDto.setPic(outPics.get(outPics.size() / 2)); + if (outPics.size() <= 5) { + districtDto.setPics(outPics); + } else { + districtDto.setPics(outPics.subList(0, 5)); + } + // districtDto.setPic(model.getPicUrl() + + // DataUtil.encodePicUrl(districtDto.getPic(), "o", "district")); + // List picsNew = new ArrayList(); + // List pics = districtDto.getPics(); + // for (String url : pics) { + // url = model.getPicUrl() + DataUtil.encodePicUrl(url, "o", + // "district"); + // picsNew.add(url); + // } + // districtDto.setPics(picsNew); + } + districtDto.setUrl("http://" + ServerAreaData.getServerAreaByDisplay(city).getSpell() + ".fangjia.com/xiaoqu-xinxi-" + + name + "-" + region); + mav.setModel(districtDto); + return mav; + } - FacetQueryResult districtDtos = new FacetQueryResult(); - for (DistrictBo bo : districtList) { - DistrictDto districtDto = new DistrictDto(bo, isSupportLatLng(request)); - DistrictHouse dh = this.districtHouseService.findDistrictHouseByDistrictKey(bo.getDistrictKey()); - if (dh != null) { - districtDto.setSellCount(dh.getSellCount()); - districtDto.setRentCount(dh.getRentCount()); - } - // Èô´æÔÚÍ⾰ͼÔòÖ»¿¼ÂÇÍ⾰ͼ - List outPics = bo.getOutPics(); - if (CollectionUtils.isNotEmpty(outPics)) { - // ±ê־ͼȡÖмäÒ»ÕÅ - districtDto.setPic(outPics.get(outPics.size() / 2)); - if (outPics.size() <= 5) { - districtDto.setPics(outPics); - } else { - districtDto.setPics(outPics.subList(0, 5)); - } - // districtDto.setPic(model.getPicUrl() + - // DataUtil.encodePicUrl(districtDto.getPic(), "s", - // "district")); - // List picsNew = new ArrayList(); - // List pics = districtDto.getPics(); - // for (String url : pics) { - // url = model.getPicUrl() + DataUtil.encodePicUrl(url, "s", - // "district"); - // picsNew.add(url); - // } - // districtDto.setPics(picsNew); - } - districtDto.setDescription(null); - districtDtos.add(districtDto); - } - districtDtos.setNumberFound(districtList.getNumberFound()); - mav.setModel(new DistrictsDto(districtDtos, ((Number) districtDtos.getNumberFound()).longValue())); - return mav; - } + public Object showListAction(DistrictSearchModel model, HttpServletRequest request) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isBlank(model.getCity())) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "Ð¡ÇøËùÔÚ³ÇÊбØÐëÊäÈë")); + return mav; + } + Pager pager = new Pager(); + int maxPageSize = OpenConfig.getConfig().getSearchListMaxPageSize(); + int maxPageIndex = OpenConfig.getConfig().getSearchListMaxPageNo(); + if (model.getPageSize() != null && model.getPageSize() > 0) { + pager.setPageSize(model.getPageSize() > maxPageSize ? maxPageSize : model.getPageSize()); + } else { + pager.setPageSize(20); + } + if (model.getPageIndex() != null && model.getPageIndex() > 1) { + int pageIndex = model.getPageIndex() > maxPageIndex ? maxPageIndex : model.getPageIndex(); + int startRow = (pageIndex - 1) * pager.getPageSize(); + pager.setStartRow(startRow); + } + FacetQueryResult result; + if (StringUtils.isBlank(model.getKeyword())) { + result = districtService.findByQueryBeanWithoutSrQuery(pager, (DistrictQueryBean) model.getQueryBean(), true); + } else { + result = districtService.findByQueryBeanWithoutSrQuery(pager, (DistrictQueryBean) model.getQueryBean(), true); + } + Map statMap = districtStatService.findDistrictStat(districtService.getDistrictKeys(result)); + FacetQueryResult districtList = new FacetQueryResult(result.size()); + for (District district : result) { + DistrictBo districtBo = new DistrictBo(district); + districtBo.setStat(statMap.get(district.getDistrictKey())); + districtList.add(districtBo); + } + districtList.setNumberFound(result.getNumberFound()); + + FacetQueryResult districtDtos = new FacetQueryResult(); + for (DistrictBo bo : districtList) { + DistrictDto districtDto = new DistrictDto(bo, isSupportLatLng(request)); + DistrictHouse dh = this.districtHouseService.findDistrictHouseByDistrictKey(bo.getDistrictKey()); + if (dh != null) { + districtDto.setSellCount(dh.getSellCount()); + districtDto.setRentCount(dh.getRentCount()); + } + // Èô´æÔÚÍ⾰ͼÔòÖ»¿¼ÂÇÍ⾰ͼ + List outPics = bo.getOutPics(); + if (CollectionUtils.isNotEmpty(outPics)) { + // ±ê־ͼȡÖмäÒ»ÕÅ + districtDto.setPic(outPics.get(outPics.size() / 2)); + if (outPics.size() <= 5) { + districtDto.setPics(outPics); + } else { + districtDto.setPics(outPics.subList(0, 5)); + } + // districtDto.setPic(model.getPicUrl() + + // DataUtil.encodePicUrl(districtDto.getPic(), "s", + // "district")); + // List picsNew = new ArrayList(); + // List pics = districtDto.getPics(); + // for (String url : pics) { + // url = model.getPicUrl() + DataUtil.encodePicUrl(url, "s", + // "district"); + // picsNew.add(url); + // } + // districtDto.setPics(picsNew); + } + districtDto.setDescription(null); + districtDtos.add(districtDto); + } + districtDtos.setNumberFound(districtList.getNumberFound()); + mav.setModel(new DistrictsDto(districtDtos, ((Number) districtDtos.getNumberFound()).longValue())); + return mav; + } /** * Ð¡Çø¾ù¼Û²éѯ½Ó¿Ú + * * @param model * @return */ - public Object avgPriceAction(AvgPriceQueryModel model){ + public Object avgPriceAction(AvgPriceQueryModel model) { RestfulModelAndView mav = new RestfulModelAndView(); mav.setViewType("rest"); if (StringUtils.isBlank(model.getCity()) || StringUtils.isBlank(model.getDistrict())) { mav.setModel(BasicModel.buildBadRequestModel("²ÎÊýȱʧ:city(³ÇÊÐ),district(ÇøÓò)ÊDZØÐë²ÎÊý")); return mav; } - if(!RegionData.isCity(model.getCity())){ - String city = RegionData.formatCity(model.getCity()); - if(null == city){ - mav.setModel(BasicModel.buildBadRequestModel("·Ç·¨³ÇÊÐ:" + model.getCity())); - return mav; - }else{ - model.setCity(city); - } - } + if (!RegionData.isCity(model.getCity())) { + String city = RegionData.formatCity(model.getCity()); + if (null == city) { + mav.setModel(BasicModel.buildBadRequestModel("·Ç·¨³ÇÊÐ:" + model.getCity())); + return mav; + } else { + model.setCity(city); + } + } String region = RegionData.formatRegion(model.getCity(), model.getDistrict()); model.setDistrict(region); - if(!RegionData.isRegion(model.getCity(), region)){ + if (!RegionData.isRegion(model.getCity(), region)) { mav.setModel(BasicModel.buildBadRequestModel("ûÓÐÕÒÄãÊäÈëµÄÇøÓò")); return mav; } - if(model.getPeriodCount() == null){ + if (model.getPeriodCount() == null) { model.setPeriodCount(1); } - if(model.getPeriodCount()< 1 || model.getPeriodCount()>156){ + if (model.getPeriodCount() < 1 || model.getPeriodCount() > 156) { mav.setModel(BasicModel.buildBadRequestModel("periodCountÖµ²»ºÏ·¨,ȡֵ·¶Î§ÊÇ£º[1-156]")); return mav; } - if(StringUtils.isBlank(model.getPeriodType())){ + if (StringUtils.isBlank(model.getPeriodType())) { model.setPeriodType("weekly"); - }else{ - if(!"weekly".equals(model.getPeriodType()) && !"monthly".equals(model.getPeriodType())){ + } else { + if (!"weekly".equals(model.getPeriodType()) && !"monthly".equals(model.getPeriodType())) { mav.setModel(BasicModel.buildBadRequestModel("periodModelÖµ·Ç·¨£¬ºÏ·¨ÖµÎª:weekly,monthly")); return mav; } } Calendar calendar = Calendar.getInstance(); - if("weekly".equals(model.getPeriodType())){ - calendar.add(Calendar.DATE, -model.getPeriodCount().intValue()*7); - }else{ + if ("weekly".equals(model.getPeriodType())) { + calendar.add(Calendar.DATE, -model.getPeriodCount().intValue() * 7); + } else { calendar.add(Calendar.MONTH, -model.getPeriodCount().intValue()); } - List regionStats = regionStatService.findRegionBlockStat(model.getCity(),model.getDistrict(),null,calendar.getTime(),new Date(),model.getPeriodType()); - if(regionStats.size() > model.getPeriodCount()){ - regionStats = regionStats.subList(regionStats.size() - model.getPeriodCount(),regionStats.size()); + List regionStats = regionStatService.findRegionBlockStat(model.getCity(), model.getDistrict(), null, calendar.getTime(), new Date(), model.getPeriodType()); + if (regionStats.size() > model.getPeriodCount()) { + regionStats = regionStats.subList(regionStats.size() - model.getPeriodCount(), regionStats.size()); } - List> result = new ArrayList>(model.getPeriodCount()); + List> result = new ArrayList>(model.getPeriodCount()); for (RegionStat regionStat : regionStats) { - Map item = new LinkedHashMap(); + Map item = new LinkedHashMap(); item.put("city", regionStat.getCity()); item.put("district", regionStat.getRegion()); item.put("block", regionStat.getBlock()); item.put("avgPrice", String.valueOf(regionStat.getAvgPrice())); - if("monthly".equals(model.getPeriodType())){ + if ("monthly".equals(model.getPeriodType())) { item.put("date", DateUtil.formatByPattern(regionStat.getWeekend(), "yyyy-MM")); - }else{ + } else { item.put("date", DateUtil.formatByPattern(regionStat.getWeekend(), "yyyy-MM-dd")); } item.put("changePercent", String.valueOf(regionStat.getMarkup() / 100d)); @@ -733,53 +733,55 @@ public class DistrictController { mav.setModel(BasicModel.buildOKModel().setResult(result)); return mav; } + /** * ÇøÓò¾ù¼Û²éѯ½Ó¿Ú + * * @param model * @return */ - public Object rentAction(AvgPriceQueryModel model){ + public Object rentAction(AvgPriceQueryModel model) { RestfulModelAndView mav = new RestfulModelAndView(); mav.setViewType("rest"); if (StringUtils.isBlank(model.getCity()) || StringUtils.isBlank(model.getDistrict())) { mav.setModel(BasicModel.buildBadRequestModel("²ÎÊýȱʧ:city(³ÇÊÐ),district(ÇøÓò)ÊDZØÐë²ÎÊý")); return mav; } - if(!RegionData.isCity(model.getCity())){ - String city = RegionData.formatCity(model.getCity()); - if(null == city){ - mav.setModel(BasicModel.buildBadRequestModel("·Ç·¨³ÇÊÐ:" + model.getCity())); - return mav; - }else{ - model.setCity(city); - } - } + if (!RegionData.isCity(model.getCity())) { + String city = RegionData.formatCity(model.getCity()); + if (null == city) { + mav.setModel(BasicModel.buildBadRequestModel("·Ç·¨³ÇÊÐ:" + model.getCity())); + return mav; + } else { + model.setCity(city); + } + } String region = RegionData.formatRegion(model.getCity(), model.getDistrict()); model.setDistrict(region); - if(!RegionData.isRegion(model.getCity(), region)){ + if (!RegionData.isRegion(model.getCity(), region)) { mav.setModel(BasicModel.buildBadRequestModel("ûÓÐÕÒÄãÊäÈëµÄÇøÓò")); return mav; } - if (model.getHouseType() == null ||model.getHouseType() < 1) { + if (model.getHouseType() == null || model.getHouseType() < 1) { mav.setModel(BasicModel.buildBadRequestModel("·¿ÎÝÀàÐͲ»ºÏ·¨")); return mav; } - if(model.getPeriodCount() == null){ + if (model.getPeriodCount() == null) { model.setPeriodCount(1); } - if(model.getPeriodCount() < 1 || model.getPeriodCount() > 72){ + if (model.getPeriodCount() < 1 || model.getPeriodCount() > 72) { mav.setModel(BasicModel.buildBadRequestModel("periodCountÖµ²»ºÏ·¨,ȡֵ·¶Î§ÊÇ£º[1-72]")); return mav; } - List regionStats = regionStatRentService.findAllByDistrictKeyAndHouseType(model.getCity(),model.getDistrict(),model.getHouseType(),model.getPeriodCount()); - if(regionStats.size() > model.getPeriodCount()){ - regionStats = regionStats.subList(regionStats.size() - model.getPeriodCount(),regionStats.size()); + List regionStats = regionStatRentService.findAllByDistrictKeyAndHouseType(model.getCity(), model.getDistrict(), model.getHouseType(), model.getPeriodCount()); + if (regionStats.size() > model.getPeriodCount()) { + regionStats = regionStats.subList(regionStats.size() - model.getPeriodCount(), regionStats.size()); } - List> result = new ArrayList>(model.getPeriodCount()); + List> result = new ArrayList>(model.getPeriodCount()); for (RegionStatRent regionStat : regionStats) { - Map item = new LinkedHashMap(); + Map item = new LinkedHashMap(); item.put("city", regionStat.getCity()); item.put("district", regionStat.getRegion()); item.put("rent", regionStat.getAvgPrice()); @@ -865,401 +867,542 @@ public class DistrictController { // mav.setModel(map); // return mav; // } - - - /** - * »ñÈ¡Ð¡ÇøµÄ¾ù¼ÛAction - * - * @param city - * @param region - * @param name - * @return - */ - public Object curAvgPriceAction(@Param(name = "city") String city, @Param(name = "region") String region, - @Param(name = "name") String name) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if (StringUtils.isBlank(city) || StringUtils.isBlank(region) || StringUtils.isBlank(name)) { - mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "Ð¡ÇøËùÔÚ³ÇÊÐ,ËùÔÚÇøÓò,Ð¡ÇøÃûΪ±ØÌîÏî")); - return mav; - } - DistrictBo districtBo = this.districtService.findByFullMode(new DistrictKey(city, region, name)); - if (null == districtBo) { - mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "Ð¡Çø²»´æÔÚ£¬Çë¼ì²é³ÇÊÐÃû,ÇøÓò,Ð¡ÇøÃû")); - return mav; - } - - - String kind = ""; - if(StringUtils.isNotBlank(districtBo.getEstateType2())){ - if(districtBo.getEstateType2().indexOf(DistrictKindEnum.bieshu.getValue())!=-1){ - kind = DistrictKindEnum.bieshu.getValue(); - } - if(districtBo.getEstateType2().indexOf("סլ")!=-1||districtBo.getEstateType2().indexOf("Ð¡Çø")!=-1){ - if(kind.length()>1){ - kind = kind + ","; - } - kind = kind + DistrictKindEnum.gongyu.getValue(); - } - districtBo.setKind(kind); - - } - if (StringUtils.isEmpty(districtBo.getKind())) { - districtBo.setKind(DistrictKindEnum.gongyu.getValue()); - } - - - String[] kinds = districtBo.getKind().split(","); - - List districtStatList = null; - List villaStatList = null; - Date date = new Date(); - if (ArrayUtils.contains(kinds, DistrictKindEnum.bieshu.getValue())) { - villaStatList = this.districtStatService.findDistrictStat( - new DistrictKey(districtBo.getCity(), districtBo.getRegion(), districtBo.getName()), - DistrictKindEnum.bieshu.getValue(), date, 1); - if (kinds.length > 1) { - districtStatList = this.districtStatService.findDistrictStat( - new DistrictKey(districtBo.getCity(), districtBo.getRegion(), districtBo.getName()), - DistrictKindEnum.gongyu.getValue(), date, 1); - } - } else { - districtStatList = this.districtStatService.findDistrictStat( - new DistrictKey(districtBo.getCity(), districtBo.getRegion(), districtBo.getName()), - DistrictKindEnum.gongyu.getValue(), date, 1); - } - if (CollectionUtils.isEmpty(districtStatList) && CollectionUtils.isEmpty(villaStatList)) { - mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "¶ÔÓ¦µÄÐ¡ÇøÎÞ¾ù¼ÛÊý¾Ý")); - return mav; - } - - DistrictStat stat = null; - if(CollectionUtils.isNotEmpty(districtStatList)){ - stat = districtStatList.get(0); - } - if(CollectionUtils.isNotEmpty(villaStatList)){ - stat = villaStatList.get(0); - } - - Map map = new HashMap(1); - map.put("avgPrice", stat.getAvgPrice()); - map.put("weekendMarkup", stat.getWeekendMarkup()); - mav.setModel(map); - return mav; - } - - /** - * »ñÈ¡Ð¡ÇøµÄÀúÊ·¾ù¼ÛAction - * - * @param city - * @param region - * @param name - * @param weekCount - * @return - */ - public Object historyPriceAction(@Param(name = "city") String city, @Param(name = "name") String name, - @Param(name = "weekCount") Integer weekCount) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - int count = OfcChartUtils.YEAR_COUNT * 7; - if (null != weekCount && weekCount > 0) { - count = weekCount; - } - if (StringUtils.isBlank(name)) { - mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "Ð¡ÇøËùÔÚ³ÇÊÐ,Ð¡ÇøÃûΪ±ØÌîÏî")); - return mav; - } - District currentDistrict = null; - city = knowbaseService.matchingCityDefaultNull(city); - if (StringUtils.isBlank(city)) { - city = "ÉϺ£"; - } - Map konwbase = knowbaseService.parseWord(name); - List> districts = (null != konwbase && null != konwbase.get("district_name")) ? (List>) konwbase - .get("district_name") : Collections.EMPTY_LIST; - if (CollectionUtils.isNotEmpty(districts)) { - for (Map district : districts) { - Map extra_data = (Map) district.get("extra_data"); - if (MapUtils.isNotEmpty(extra_data)) { - String region = (String) extra_data.get("region"); - name = (String) district.get("value"); - String tempCity = (String) extra_data.get("city"); - if (!city.equals(tempCity)) { - continue; - } - District d = districtService.findDistrict(new DistrictKey(city, region, name), false); - if (null == d) { - continue; - } - currentDistrict = d; - break; - } - } - } - - if (null == currentDistrict) { - mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "δÕÒµ½Ïà¹ØÐ¡ÇøÐÅÏ¢")); - return mav; - } - - // ½âÎö³ö³ÇÊÐÇøÓòÐ¡ÇøÃûÂ¥¶°ºÅ - DistrictBo districtBo = this.districtService.findByFullMode(new DistrictKey(currentDistrict.getCity(), currentDistrict - .getRegion(), currentDistrict.getName())); - if (null == districtBo) { - mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "Ð¡Çø²»´æÔÚ£¬Çë¼ì²é³ÇÊÐÃû,Ð¡ÇøÃû")); - return mav; - } - if (StringUtils.isEmpty(districtBo.getKind())) { - districtBo.setKind(DistrictKindEnum.gongyu.getValue()); - } - String[] kinds = districtBo.getKind().split(","); - List districtStatList = null; - List villaStatList = null; - Date date = new Date(); - if (ArrayUtils.contains(kinds, DistrictKindEnum.bieshu.getValue())) { - villaStatList = this.districtStatService.findDistrictStat( - new DistrictKey(districtBo.getCity(), districtBo.getRegion(), districtBo.getName()), - DistrictKindEnum.bieshu.getValue(), date, count); - if (kinds.length > 1) { - districtStatList = this.districtStatService.findDistrictStat( - new DistrictKey(districtBo.getCity(), districtBo.getRegion(), districtBo.getName()), - DistrictKindEnum.gongyu.getValue(), date, count); - } - } else { - districtStatList = this.districtStatService.findDistrictStat( - new DistrictKey(districtBo.getCity(), districtBo.getRegion(), districtBo.getName()), - DistrictKindEnum.gongyu.getValue(), date, count); - } - if (CollectionUtils.isEmpty(districtStatList) && CollectionUtils.isEmpty(villaStatList)) { - mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "¶ÔÓ¦µÄÐ¡ÇøÎÞ¾ù¼ÛÊý¾Ý")); - return mav; - } - districtStatList = (List) OfcChartUtils.fixYDatas(date, districtStatList, count, null); - villaStatList = (List) OfcChartUtils.fixYDatas(date, villaStatList, count, null); - Map map = new HashMap(1); - map.put("stat", - DtoConverter.convertFromDistrictBoList(DataUtil.descCollection(districtStatList), - DataUtil.descCollection(villaStatList))); - mav.setModel(map); - return mav; - } - - /** - * ¸ù¾ÝÐ¡ÇøÃûµÈ»ñÈ¡Ð¡ÇøÊôÐÔ - * - * @param uniqueCodes - * @param districtNames - * @param regionNames - * @param cityNames - * @return - */ - public Object fetchDistrictsPropertiesAction(@Param(name = "uniqueCodes") String[] uniqueCodes, - @Param(name = "districtNames") String[] districtNames, @Param(name = "regionNames") String[] regionNames, - @Param(name = "cityNames") String[] cityNames) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - - if (uniqueCodes.length * districtNames.length * regionNames.length * cityNames.length == 0) { - mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "Ð¡ÇøÎ¨Ò»Âë¡¢Ð¡ÇøÃû¡¢Ð¡ÇøËùÔÚÇøÓò¡¢Ð¡ÇøËùÔÚ³ÇÊбØÌî")); - return mav; - } - if (uniqueCodes.length - districtNames.length + regionNames.length - cityNames.length != 0) { - mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "Ð¡ÇøÎ¨Ò»ÂëÊý×é¡¢Ð¡ÇøÃûÊý×é¡¢Ð¡ÇøËùÔÚÇøÓòÊý×é¡¢Ð¡ÇøËùÔÚ³ÇÊÐÊý×éÊýÁ¿±ØÐëÏàͬ")); - return mav; - } - - ArrayList keys = new ArrayList(1); - Map key_uniqueCode = new HashMap(1); - for (int i = 0; i < cityNames.length; i++) { - cityNames[i] = this.knowbaseService.matchingCity(cityNames[i]); - regionNames[i] = this.knowbaseService.matchingRegion(regionNames[i], cityNames[i]); - DistrictKey key = new DistrictKey(cityNames[i], regionNames[i], districtNames[i]); - keys.add(key); - key_uniqueCode.put(key, uniqueCodes[i]); - } - Map districtMap = this.districtService.findDistrictByKeyList(keys, false); - Map newDistrictMap = this.districtService.findDistrictByKeyList(keys, true, false); - - Map dtoMap = new HashMap(1); - for (DistrictKey key : districtMap.keySet()) { - District d = districtMap.get(key); - if (null != d) { - String uniqueCode = key_uniqueCode.get(key); - DistrictsPropertiesDto dto = new DistrictsPropertiesDto(); - dto.setUniqueCode(uniqueCode); - dto.setDistrictName(d.getName()); - if (null != newDistrictMap.get(key)) { - dto.setNewDistrict(true); - if (d.getStatus() == 5) { - dto.setOnSale(true); - } - if (StringUtils.isNotBlank(d.getDiscount())) { - dto.setDiscount(true); - } - } - if (null == dto.getOnSale()) { - DistrictHouse dh = this.districtHouseService.findDistrictHouseByDistrictKey(key); - if (dh != null && dh.getSellCount() != 0) { - dto.setOnSale(true); - } - } - if (StringUtils.isNotBlank(d.getVideoUrl())) { - dto.setVideo(true); - } - dtoMap.put(uniqueCode, dto); - } - } - mav.setModel(dtoMap); - return mav; - } - - private boolean isRadiusSearch(DistrictSearchModel model) { - return null != model.getRadius() && model.getRadius() > 0 && StringUtils.isNotBlank(model.getCity()) - && model.getLat() != null && model.getLng() != null && model.getLat() != 0 && model.getLng() != 0; - } - - public Object uploadAction(@Param(name = "token") String token, @Param(name = "data") String data) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - - Map ret = new HashMap(1); - ret.put("RESULT", 500); - - ApiUser apiUser = checkNewAuthorized(token); - if (null == apiUser) { - return mav; - } - - try { - JSONArray disJsonArr = JSONArray.fromObject(data); - for (int i = 0; i < disJsonArr.size(); i++) { - JSONObject disJsonObj = disJsonArr.getJSONObject(i); - ExtractDistrict dis = (ExtractDistrict) JSONObject.toBean(disJsonObj, ExtractDistrict.class); - dis.setSource("open_api"); - dis.setUserId((int) apiUser.getId()); - dis.setCreationDate(new Date()); - dis.setModificationDate(dis.getCreationDate()); - extractDistrictService.save(dis); - } - } catch (JSONException e) { - return mav; - } - - ret.put("RESULT", 200); - return mav; - } - - public Object facilitysAction(DistrictSearchModel model, @Param(name = "city") String city, @Param(name = "region") String region, - @Param(name = "name") String name, HttpServletRequest request) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if (StringUtils.isBlank(name) || StringUtils.isBlank(city) || StringUtils.isBlank(region)) { - mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "Ð¡ÇøËùÔÚ³ÇÊÐ,Ð¡ÇøÃû,ËùÔÚÇøÓò±Ø±ØÐëÊäÈë")); - return mav; - } else { - District districtBo = districtService.findDistrict(new DistrictKey(city, region, name), "district"); - if (null == districtBo) { - mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "Ð¡ÇøÊý¾Ý²»´æÔÚ")); - return mav; - } - DistrictFacilitys facilitys = districtFacilitysService.findByDistrict(districtBo); - mav.setModel(BasicModel.buildOKModel().setResult(facilitys)); - } - return mav; - } - public Object addrFacilitysAction(DistrictSearchModel model, @Param(name = "city") String city, @Param(name = "address") String address) throws Exception{ - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if (StringUtils.isBlank(address)) { - mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "µØÖ·±ØÐëÊäÈë")); - return mav; - } else { - String cat = "district"; + /** + * »ñÈ¡Ð¡ÇøµÄ¾ù¼ÛAction + * + * @param city + * @param region + * @param name + * @return + */ + public Object curAvgPriceAction(@Param(name = "city") String city, @Param(name = "region") String region, + @Param(name = "name") String name) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isBlank(city) || StringUtils.isBlank(region) || StringUtils.isBlank(name)) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "Ð¡ÇøËùÔÚ³ÇÊÐ,ËùÔÚÇøÓò,Ð¡ÇøÃûΪ±ØÌîÏî")); + return mav; + } + DistrictBo districtBo = this.districtService.findByFullMode(new DistrictKey(city, region, name)); + if (null == districtBo) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "Ð¡Çø²»´æÔÚ£¬Çë¼ì²é³ÇÊÐÃû,ÇøÓò,Ð¡ÇøÃû")); + return mav; + } - HttpRequest request = new HttpRequest(); - JSONObject json = null; - Map params = new HashMap(); - params.put("city", city); - params.put("address", address); - params.put("category", "property"); - //ÐÂÆ¥Åä½Ó¿Ú - json = request.getJsonContent("http://192.168.0.100:32080/FangJiaNlpService/match", params, "UTF-8"); - District property = null; - if (json != null && json.size() > 0) { - MatchedBuildingDto dto = CommonDtoUtils.transformV(MatchedBuildingDto.class, json); - property = districtService.findByNameAndAlias(dto.getCity(), dto.getDistrict(), dto.getName(), cat); - if (null == property) { - mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "Ð¡ÇøÊý¾Ý²»´æÔÚ")); - return mav; - } - DistrictFacilitys facilitys = districtFacilitysService.findByDistrict(property); - mav.setModel(BasicModel.buildOKModel().setResult(facilitys)); - }else{ - mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "Ð¡ÇøÊý¾Ý²»´æÔÚ")); - } - } - return mav; - } - - - /** - * аætokenÑéÖ¤ - * - * @param token - * @return - */ - private ApiUser checkNewAuthorized(String token) { - Map tokenMap = FangjiaApiUtil.parseToken(token); - if (tokenMap == null) { - return null; - } - // tokenÑéÖ¤ºó£¬ÄÃÈ¡³öµÄ×Ö¶ÎÔÙÈ¥Êý¾Ý¿âÑéÖ¤Ò»±é - if (StringUtils.isNotBlank(tokenMap.get("userid")) && !"null".equals(tokenMap.get("userid"))) { - List params = new ArrayList(); - params.add(new QueryParam("ID", tokenMap.get("userid"))); - ApiUser apiUser = apiUserService.findApiUserById(Long.parseLong(tokenMap.get("userid"))); - if (apiUser != null) { - if (tokenMap.get("appKey").equals(apiUser.getAppKey())) { - return apiUser; - } - } - } - return null; - } - public void setDistrictService(DistrictService districtService) { - this.districtService = districtService; - } + String kind = ""; + if (StringUtils.isNotBlank(districtBo.getEstateType2())) { + if (districtBo.getEstateType2().indexOf(DistrictKindEnum.bieshu.getValue()) != -1) { + kind = DistrictKindEnum.bieshu.getValue(); + } + if (districtBo.getEstateType2().indexOf("סլ") != -1 || districtBo.getEstateType2().indexOf("Ð¡Çø") != -1) { + if (kind.length() > 1) { + kind = kind + ","; + } + kind = kind + DistrictKindEnum.gongyu.getValue(); + } + districtBo.setKind(kind); - public void setDistrictStatService(DistrictStatService districtStatService) { - this.districtStatService = districtStatService; - } + } + if (StringUtils.isEmpty(districtBo.getKind())) { + districtBo.setKind(DistrictKindEnum.gongyu.getValue()); + } - public void setDistrictHouseService(DistrictHouseService districtHouseService) { - this.districtHouseService = districtHouseService; - } - public void setAutoCompleteService(AutoCompleteService autoCompleteService) { - this.autoCompleteService = autoCompleteService; - } + String[] kinds = districtBo.getKind().split(","); - public void setMenuService(MenuService menuService) { - this.menuService = menuService; - } + List districtStatList = null; + List villaStatList = null; + Date date = new Date(); + if (ArrayUtils.contains(kinds, DistrictKindEnum.bieshu.getValue())) { + villaStatList = this.districtStatService.findDistrictStat( + new DistrictKey(districtBo.getCity(), districtBo.getRegion(), districtBo.getName()), + DistrictKindEnum.bieshu.getValue(), date, 1); + if (kinds.length > 1) { + districtStatList = this.districtStatService.findDistrictStat( + new DistrictKey(districtBo.getCity(), districtBo.getRegion(), districtBo.getName()), + DistrictKindEnum.gongyu.getValue(), date, 1); + } + } else { + districtStatList = this.districtStatService.findDistrictStat( + new DistrictKey(districtBo.getCity(), districtBo.getRegion(), districtBo.getName()), + DistrictKindEnum.gongyu.getValue(), date, 1); + } + if (CollectionUtils.isEmpty(districtStatList) && CollectionUtils.isEmpty(villaStatList)) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "¶ÔÓ¦µÄÐ¡ÇøÎÞ¾ù¼ÛÊý¾Ý")); + return mav; + } - public void setKnowbaseService(KnowbaseService knowbaseService) { - this.knowbaseService = knowbaseService; - } + DistrictStat stat = null; + if (CollectionUtils.isNotEmpty(districtStatList)) { + stat = districtStatList.get(0); + } + if (CollectionUtils.isNotEmpty(villaStatList)) { + stat = villaStatList.get(0); + } - public void setApiUserService(ApiUserService apiUserService) { - this.apiUserService = apiUserService; - } + Map map = new HashMap(1); + map.put("avgPrice", stat.getAvgPrice()); + map.put("weekendMarkup", stat.getWeekendMarkup()); + mav.setModel(map); + return mav; + } - public void setExtractDistrictService(ExtractDistrictService extractDistrictService) { - this.extractDistrictService = extractDistrictService; - } + /** + * »ñÈ¡Ð¡ÇøµÄÀúÊ·¾ù¼ÛAction + * + * @param city + * @param region + * @param name + * @param weekCount + * @return + */ + public Object historyPriceAction(@Param(name = "city") String city, @Param(name = "name") String name, + @Param(name = "weekCount") Integer weekCount) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + int count = OfcChartUtils.YEAR_COUNT * 7; + if (null != weekCount && weekCount > 0) { + count = weekCount; + } + if (StringUtils.isBlank(name)) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "Ð¡ÇøËùÔÚ³ÇÊÐ,Ð¡ÇøÃûΪ±ØÌîÏî")); + return mav; + } + District currentDistrict = null; + city = knowbaseService.matchingCityDefaultNull(city); + if (StringUtils.isBlank(city)) { + city = "ÉϺ£"; + } + Map konwbase = knowbaseService.parseWord(name); + List> districts = (null != konwbase && null != konwbase.get("district_name")) ? (List>) konwbase + .get("district_name") : Collections.EMPTY_LIST; + if (CollectionUtils.isNotEmpty(districts)) { + for (Map district : districts) { + Map extra_data = (Map) district.get("extra_data"); + if (MapUtils.isNotEmpty(extra_data)) { + String region = (String) extra_data.get("region"); + name = (String) district.get("value"); + String tempCity = (String) extra_data.get("city"); + if (!city.equals(tempCity)) { + continue; + } + District d = districtService.findDistrict(new DistrictKey(city, region, name), false); + if (null == d) { + continue; + } + currentDistrict = d; + break; + } + } + } + + if (null == currentDistrict) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "δÕÒµ½Ïà¹ØÐ¡ÇøÐÅÏ¢")); + return mav; + } + + // ½âÎö³ö³ÇÊÐÇøÓòÐ¡ÇøÃûÂ¥¶°ºÅ + DistrictBo districtBo = this.districtService.findByFullMode(new DistrictKey(currentDistrict.getCity(), currentDistrict + .getRegion(), currentDistrict.getName())); + if (null == districtBo) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "Ð¡Çø²»´æÔÚ£¬Çë¼ì²é³ÇÊÐÃû,Ð¡ÇøÃû")); + return mav; + } + if (StringUtils.isEmpty(districtBo.getKind())) { + districtBo.setKind(DistrictKindEnum.gongyu.getValue()); + } + String[] kinds = districtBo.getKind().split(","); + List districtStatList = null; + List villaStatList = null; + Date date = new Date(); + if (ArrayUtils.contains(kinds, DistrictKindEnum.bieshu.getValue())) { + villaStatList = this.districtStatService.findDistrictStat( + new DistrictKey(districtBo.getCity(), districtBo.getRegion(), districtBo.getName()), + DistrictKindEnum.bieshu.getValue(), date, count); + if (kinds.length > 1) { + districtStatList = this.districtStatService.findDistrictStat( + new DistrictKey(districtBo.getCity(), districtBo.getRegion(), districtBo.getName()), + DistrictKindEnum.gongyu.getValue(), date, count); + } + } else { + districtStatList = this.districtStatService.findDistrictStat( + new DistrictKey(districtBo.getCity(), districtBo.getRegion(), districtBo.getName()), + DistrictKindEnum.gongyu.getValue(), date, count); + } + if (CollectionUtils.isEmpty(districtStatList) && CollectionUtils.isEmpty(villaStatList)) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "¶ÔÓ¦µÄÐ¡ÇøÎÞ¾ù¼ÛÊý¾Ý")); + return mav; + } + districtStatList = (List) OfcChartUtils.fixYDatas(date, districtStatList, count, null); + villaStatList = (List) OfcChartUtils.fixYDatas(date, villaStatList, count, null); + Map map = new HashMap(1); + map.put("stat", + DtoConverter.convertFromDistrictBoList(DataUtil.descCollection(districtStatList), + DataUtil.descCollection(villaStatList))); + mav.setModel(map); + return mav; + } + + /** + * ¸ù¾ÝÐ¡ÇøÃûµÈ»ñÈ¡Ð¡ÇøÊôÐÔ + * + * @param uniqueCodes + * @param districtNames + * @param regionNames + * @param cityNames + * @return + */ + public Object fetchDistrictsPropertiesAction(@Param(name = "uniqueCodes") String[] uniqueCodes, + @Param(name = "districtNames") String[] districtNames, @Param(name = "regionNames") String[] regionNames, + @Param(name = "cityNames") String[] cityNames) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + + if (uniqueCodes.length * districtNames.length * regionNames.length * cityNames.length == 0) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "Ð¡ÇøÎ¨Ò»Âë¡¢Ð¡ÇøÃû¡¢Ð¡ÇøËùÔÚÇøÓò¡¢Ð¡ÇøËùÔÚ³ÇÊбØÌî")); + return mav; + } + if (uniqueCodes.length - districtNames.length + regionNames.length - cityNames.length != 0) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "Ð¡ÇøÎ¨Ò»ÂëÊý×é¡¢Ð¡ÇøÃûÊý×é¡¢Ð¡ÇøËùÔÚÇøÓòÊý×é¡¢Ð¡ÇøËùÔÚ³ÇÊÐÊý×éÊýÁ¿±ØÐëÏàͬ")); + return mav; + } + + ArrayList keys = new ArrayList(1); + Map key_uniqueCode = new HashMap(1); + for (int i = 0; i < cityNames.length; i++) { + cityNames[i] = this.knowbaseService.matchingCity(cityNames[i]); + regionNames[i] = this.knowbaseService.matchingRegion(regionNames[i], cityNames[i]); + DistrictKey key = new DistrictKey(cityNames[i], regionNames[i], districtNames[i]); + keys.add(key); + key_uniqueCode.put(key, uniqueCodes[i]); + } + Map districtMap = this.districtService.findDistrictByKeyList(keys, false); + Map newDistrictMap = this.districtService.findDistrictByKeyList(keys, true, false); + + Map dtoMap = new HashMap(1); + for (DistrictKey key : districtMap.keySet()) { + District d = districtMap.get(key); + if (null != d) { + String uniqueCode = key_uniqueCode.get(key); + DistrictsPropertiesDto dto = new DistrictsPropertiesDto(); + dto.setUniqueCode(uniqueCode); + dto.setDistrictName(d.getName()); + if (null != newDistrictMap.get(key)) { + dto.setNewDistrict(true); + if (d.getStatus() == 5) { + dto.setOnSale(true); + } + if (StringUtils.isNotBlank(d.getDiscount())) { + dto.setDiscount(true); + } + } + if (null == dto.getOnSale()) { + DistrictHouse dh = this.districtHouseService.findDistrictHouseByDistrictKey(key); + if (dh != null && dh.getSellCount() != 0) { + dto.setOnSale(true); + } + } + if (StringUtils.isNotBlank(d.getVideoUrl())) { + dto.setVideo(true); + } + dtoMap.put(uniqueCode, dto); + } + } + mav.setModel(dtoMap); + return mav; + } + + private boolean isRadiusSearch(DistrictSearchModel model) { + return null != model.getRadius() && model.getRadius() > 0 && StringUtils.isNotBlank(model.getCity()) + && model.getLat() != null && model.getLng() != null && model.getLat() != 0 && model.getLng() != 0; + } + + public Object uploadAction(@Param(name = "token") String token, @Param(name = "data") String data) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + + Map ret = new HashMap(1); + ret.put("RESULT", 500); + + ApiUser apiUser = checkNewAuthorized(token); + if (null == apiUser) { + return mav; + } + + try { + JSONArray disJsonArr = JSONArray.fromObject(data); + for (int i = 0; i < disJsonArr.size(); i++) { + JSONObject disJsonObj = disJsonArr.getJSONObject(i); + ExtractDistrict dis = (ExtractDistrict) JSONObject.toBean(disJsonObj, ExtractDistrict.class); + dis.setSource("open_api"); + dis.setUserId((int) apiUser.getId()); + dis.setCreationDate(new Date()); + dis.setModificationDate(dis.getCreationDate()); + extractDistrictService.save(dis); + } + } catch (JSONException e) { + return mav; + } + + ret.put("RESULT", 200); + return mav; + } + + public Object facilitysAction(DistrictSearchModel model, @Param(name = "city") String city, @Param(name = "region") String region, + @Param(name = "name") String name, HttpServletRequest request) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isBlank(name) || StringUtils.isBlank(city) || StringUtils.isBlank(region)) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "Ð¡ÇøËùÔÚ³ÇÊÐ,Ð¡ÇøÃû,ËùÔÚÇøÓò±Ø±ØÐëÊäÈë")); + return mav; + } else { + District districtBo = districtService.findDistrict(new DistrictKey(city, region, name), "district"); + if (null == districtBo) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "Ð¡ÇøÊý¾Ý²»´æÔÚ")); + return mav; + } + DistrictFacilitys facilitys = districtFacilitysService.findByDistrict(districtBo); + mav.setModel(BasicModel.buildOKModel().setResult(facilitys)); + } + return mav; + } + + // ±£´æÖܱßÅäÌ× + public Object saveFacilitiesAction(DistrictFacilitysModel model) { + model = processParam(model); + if (StringUtils.isNotBlank(model.getId())) { + Map data = new HashMap(); + data.put("kindergarten", model.getKindergarten()); + data.put("primarySchool", model.getPrimarySchool()); + data.put("middleSchool", model.getMiddleSchool()); + data.put("university", model.getUniversity()); + data.put("hospital", model.getHospital()); + data.put("shop", model.getShop()); + data.put("supermarket", model.getSupermarket()); + data.put("foodShop", model.getFoodShop()); + data.put("bus", model.getBus()); + data.put("bank", model.getBank()); + data.put("atm", model.getAtm()); + data.put("metro",model.getMetro()); + districtService.updateDistrictFacilitysById(data, model.getId()); + } else { + DistrictFacilitys districtFacilitys = CommonDtoUtils.transformV(DistrictFacilitys.class, model); + districtService.saveDistrictFacilitys(districtFacilitys); + } + return null; + } + + public static List convertToList(String value) { + List result = new ArrayList(); + + if (value != null && !value.isEmpty()) { + value = value.replaceAll("\\[", "").replaceAll("]", "").replaceAll(" ",""); + String[] splitValues = value.split(","); // °´¶ººÅ·Ö¸î + + // ±éÀúÊý×é²¢¹ýÂË¿Õ×Ö·û´® + for (String str : splitValues) { + if (!str.isEmpty()) { // Ö»Ìí¼Ó·Ç¿Õ×Ö·û´® + result.add(str); + } + } + } + + return result.isEmpty() ? null : result; // Èç¹û½á¹ûΪ¿Õ£¬Ôò·µ»Ø null + } + + public static DistrictFacilitysModel processParam(DistrictFacilitysModel model) { + // ´¦Àíÿ¸ö×ֶΣ¬È·±£Ö»ÓÐ·Ç null ×ֶβŽøÐд¦Àí + if (model.getKindergarten() != null) { + model.setKindergarten(convertToList(model.getKindergarten().toString())); + } + + if (model.getPrimarySchool() != null) { + model.setPrimarySchool(convertToList(model.getPrimarySchool().toString())); + } + + if (model.getMiddleSchool() != null) { + model.setMiddleSchool(convertToList(model.getMiddleSchool().toString())); + } + + if (model.getUniversity() != null) { + model.setUniversity(convertToList(model.getUniversity().toString())); + } + + if (model.getHospital() != null) { + model.setHospital(convertToList(model.getHospital().toString())); + } + + if (model.getShop() != null) { + model.setShop(convertToList(model.getShop().toString())); + } + + if (model.getSupermarket() != null) { + model.setSupermarket(convertToList(model.getSupermarket().toString())); + } + + if (model.getFoodShop() != null) { + model.setFoodShop(convertToList(model.getFoodShop().toString())); + } + + if (model.getBus() != null) { + model.setBus(convertToList(model.getBus().toString())); + } + + if (model.getBank() != null) { + model.setBank(convertToList(model.getBank().toString())); + } + + if (model.getAtm() != null) { + model.setAtm(convertToList(model.getAtm().toString())); + } + if (model.getMetro() != null) { + model.setMetro(convertToList(model.getMetro().toString())); + } + return model; + } + + /** + * »ñÈ¡Ð¡ÇøÍ¼Æ¬ + * + * @param districtModel + * @return + */ + public Object listPicAction(DistrictModel districtModel) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isBlank(districtModel.getId())) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "ID±ØÐëÊäÈë")); + return mav; + } + SeaweedImages seaweedImages = seaweedImagesService.findById(districtModel.getId()); + if (seaweedImages != null) { + mav.setModel(BasicModel.buildOKModel().setResult(seaweedImages)); + } else { + mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "ͼƬÊý¾Ý²»´æÔÚ")); + } + return mav; + } + public Object deletePicAction(DistrictModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isBlank(model.getId())) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "ID±ØÐëÊäÈë")); + return mav; + } + seaweedImagesService.deleteImage(model.getId(),model.getUrl(),model.getPicType(), model.getRoomType()); + mav.setModel(new HttpCode(OpenHttpCodeEnum.OK, "ɾ³ý³É¹¦")); + return mav; + } + public Object addPicAction(DistrictModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (model.getImageUrls()!=null){ + model.setImageUrls(convertToList(model.getImageUrls().toString())); + } + if (StringUtils.isBlank(model.getId())) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "ID±ØÐëÊäÈë")); + return mav; + } + seaweedImagesService.addImage(model.getId(),model.getImageUrls(),model.getPicType(), model.getRoomType()); + mav.setModel(new HttpCode(OpenHttpCodeEnum.OK, "Ìí¼Ó³É¹¦")); + return mav; + } + + + public Object addrFacilitysAction(DistrictSearchModel model, @Param(name = "city") String city, @Param(name = "address") String address) throws Exception { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isBlank(address)) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "µØÖ·±ØÐëÊäÈë")); + return mav; + } else { + String cat = "district"; + + HttpRequest request = new HttpRequest(); + JSONObject json = null; + Map params = new HashMap(); + params.put("city", city); + params.put("address", address); + params.put("category", "property"); + //ÐÂÆ¥Åä½Ó¿Ú + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaNlpService/match", params, "UTF-8"); + District property = null; + if (json != null && json.size() > 0) { + MatchedBuildingDto dto = CommonDtoUtils.transformV(MatchedBuildingDto.class, json); + property = districtService.findByNameAndAlias(dto.getCity(), dto.getDistrict(), dto.getName(), cat); + if (null == property) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "Ð¡ÇøÊý¾Ý²»´æÔÚ")); + return mav; + } + DistrictFacilitys facilitys = districtFacilitysService.findByDistrict(property); + mav.setModel(BasicModel.buildOKModel().setResult(facilitys)); + } else { + mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "Ð¡ÇøÊý¾Ý²»´æÔÚ")); + } + } + return mav; + } + + + /** + * аætokenÑéÖ¤ + * + * @param token + * @return + */ + private ApiUser checkNewAuthorized(String token) { + Map tokenMap = FangjiaApiUtil.parseToken(token); + if (tokenMap == null) { + return null; + } + // tokenÑéÖ¤ºó£¬ÄÃÈ¡³öµÄ×Ö¶ÎÔÙÈ¥Êý¾Ý¿âÑéÖ¤Ò»±é + if (StringUtils.isNotBlank(tokenMap.get("userid")) && !"null".equals(tokenMap.get("userid"))) { + List params = new ArrayList(); + params.add(new QueryParam("ID", tokenMap.get("userid"))); + ApiUser apiUser = apiUserService.findApiUserById(Long.parseLong(tokenMap.get("userid"))); + if (apiUser != null) { + if (tokenMap.get("appKey").equals(apiUser.getAppKey())) { + return apiUser; + } + } + } + return null; + } + + public void setDistrictService(DistrictService districtService) { + this.districtService = districtService; + } + + public void setDistrictStatService(DistrictStatService districtStatService) { + this.districtStatService = districtStatService; + } + + public void setDistrictHouseService(DistrictHouseService districtHouseService) { + this.districtHouseService = districtHouseService; + } + + public void setAutoCompleteService(AutoCompleteService autoCompleteService) { + this.autoCompleteService = autoCompleteService; + } + + public void setMenuService(MenuService menuService) { + this.menuService = menuService; + } + + public void setKnowbaseService(KnowbaseService knowbaseService) { + this.knowbaseService = knowbaseService; + } + + public void setApiUserService(ApiUserService apiUserService) { + this.apiUserService = apiUserService; + } + + public void setExtractDistrictService(ExtractDistrictService extractDistrictService) { + this.extractDistrictService = extractDistrictService; + } public DistrictService getDistrictService() { return districtService; @@ -1285,7 +1428,11 @@ public class DistrictController { this.regionStatRentService = regionStatRentService; } - public void setDistrictFacilitysService(DistrictFacilitysService districtFacilitysService) { - this.districtFacilitysService = districtFacilitysService; - } + public void setDistrictFacilitysService(DistrictFacilitysService districtFacilitysService) { + this.districtFacilitysService = districtFacilitysService; + } + + public void setSeaweedImagesService(SeaweedImagesService seaweedImagesService) { + this.seaweedImagesService = seaweedImagesService; + } } diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/FshController.java b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/FshController.java index d5d69a1af..c8b8b64ad 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/FshController.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/FshController.java @@ -1925,8 +1925,12 @@ public class FshController { evaluation.setFitmentCharge(model.getDecorationCost()); } evaluation.setGardenArea(model.getGardenArea()); - if (0 != model.getHall()) { - evaluation.setHall(model.getHall()); + try { + if (0 != model.getHall()) { + evaluation.setHall(model.getHall()); + } + } catch (Exception ex) { + } if (null != model.getFloor()) { evaluation.setFloor(model.getFloor()); @@ -1951,7 +1955,7 @@ public class FshController { evaluation.setOtherFactor(model.getOtherFactor()); } evaluation.setRegion(model.getDistrict()); - if (0 != model.getRoom()) { + if (model.getRoom() != null && 0 != model.getRoom()) { evaluation.setRoom(model.getRoom()); } if (StringUtils.isNotBlank(model.getRoomNumber())) { diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/GdBankController.java b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/GdBankController.java index fd1709bf3..8745f5969 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/GdBankController.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/GdBankController.java @@ -51,7 +51,45 @@ public class GdBankController { }; /** - * ÉæÅ©Ê¶±ð-йæÔò-¹â´óÒøÐÐ + * ÅжÏËùÊôÇøÓò + * + * @param map + * @return + */ + public String addrArea(Map map, String type) { + if (map.get("verifyFlag") == null) { + return ""; + } + if (map.get("verifyFlag").equals("·ÇÅ©")) { + return "³ÇÊÐÇøÓò"; + } + if (map.get("verifyFlag").equals("Å©")) { + return "Å©´åÇøÓò"; + } + if ("2".equals(type) && "ÊÇ".equals(map.get("countyGov"))) { + return "ÏØ³Ç³ÇÇø"; + } + return ""; + } + + /** + * ÅжÏÏØ¼¶ÊÐ + */ + public String countyLevelCity(Map map) { + if (map.get("city") == null) { + return ""; + } + if (map.get("city").endsWith("Çø")) { + return "·ñ"; + } + if (map.get("city").equals("¶«Ý¸ÊÐ") || map.get("city").equals("¼ÎÓø¹ØÊÐ") || map.get("city").equals("ÖÐɽÊÐ") || map.get("city").equals("ÙÙÖÝÊÐ")) { + return "·ñ"; + } + return "ÊÇ"; + } + + /** + * ÉæÅ©Ê¶±ð-йæÔò-¹â´óÒøÐжԹ«Ê¶±ð½Ó¿Ú * * @param model * @return @@ -70,15 +108,15 @@ public class GdBankController { JSONObject json = null; Map params = new HashMap(); params.put("city", StringUtils.isNotBlank(model.getCity()) ? model.getCity() : null); - params.put("type", type); - params.put("redis", (model.getRadius() != null && model.getRadius() != 0) ? model.getRadius().toString() : null); + //params.put("type", type); + //params.put("redis", (model.getRadius() != null && model.getRadius() != 0) ? model.getRadius().toString() : null); params.put("address", model.getAddress()); - params.put("showFullValue", "2"); + //params.put("showFullValue", "2"); try { - json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/villageIdentify", params, "UTF-8"); + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/cebEnterpriseVillageIdentify", params, "UTF-8"); } catch (Exception e) { try { - json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/villageIdentify", params, "UTF-8"); + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/cebEnterpriseVillageIdentify", params, "UTF-8"); } catch (Exception ex) { ex.printStackTrace(); } @@ -90,61 +128,67 @@ public class GdBankController { if (json.containsKey("result")) { //ÎÒÃǵĽá¹û JSONObject result = json.getJSONObject("result"); - if (("ÊÇ").equals(result.get("countyLevelCity"))) { - result.put("prefectureLevelCity", "·ñ"); - } else if (("·ñ").equals(result.get("countyLevelCity"))) { - result.put("prefectureLevelCity", "ÊÇ"); - } - // Èç¹ûÊÇÎÞЧÐÅÏ¢»òÕßûÓÐÐÐÕþÇø»®£¬ÔòÓÃÎÒÃÇµÄ - if (result.containsKey("addrVerify") && ("ÎÞЧ".equals(result.getString("addrVerify")) || "ûÓÐÐÐÕþÇø»®".equals(result.getString("addrVerify")))) { - basicModel.setResult(result); - //ÎÒÃÇÊ¡¼¶¼°ÒÔÉÏÓпª·¢Çø£¬Ö±½ÓÓÃÎÒÃǵĽá¹û - } else if (result.containsKey("devDistrictName")) { - basicModel.setResult(result); - } else { - try { - //Èç¹ûÊǽ­ËÕÊ¡»òÕßÕã½­Ê¡ µ÷ÓÃÆëÁºµÄ½á¹û - if ("½­ËÕÊ¡".equals(result.getString("province")) || "Õã½­Ê¡".equals(result.getString("province"))) { + //ÎÒÃÇÊ¡¼¶¼°ÒÔÉÏÓпª·¢Çø£¬Ö±½ÓÓÃÎÒÃǵĽá¹û + basicModel.setResult(result); +// if (result.containsKey("devDistrictName")) { +// } else { +// try { +// // ÎÒÃÇÊÇÏØÕþ¸®£¬ÇÒɿũ½á¹ûΪũ£¬È¡ÎÒÃǽá¹û£¬ÒòΪ¹â´ó²¿·ÖÂß¼­µ÷Õû +// if ("ÊÇ".equals(result.get("countyGov")) && "Å©".equals(result.get("verifyFlag"))) { +// basicModel.setResult(result); +// mav.setModel(basicModel); +// return mav; +// } +// //Èç¹ûÊǽ­ËÕÊ¡»òÕßÕã½­Ê¡ µ÷ÓÃÆëÁºµÄ½á¹û +// if ("½­ËÕÊ¡".equals(result.getString("province")) || "Õã½­Ê¡".equals(result.getString("province"))) { +// //½á¹û±È½Ï£¬Èç¹ûɿũ½á¹û²»Ò»Ö +// //µ÷ÓÃÆëÁº type £º1 ¶Ô¹« 0 ¶Ô˽ +// //ÎÒÃÇ type £º1 ¶Ô˽ 2 ¶Ô¹² +// String qltype = "2".equals(type) ? "1" : "0"; +// Map map = senRequest(address, qltype); +// // ɿũ½á¹û²»Ò»Ñù +// if (!map.get("verifyFlag").equals(result.get("verifyFlag"))) { +// // ÆëÁºÏØÕþ¸®µ«ÊÇÉæÅ©ÎªÅ©£¬È¡ÎÒÃǵĽá¹û ÑïÖÐÊÐÈýé½ÖµÀÖлª´åÓÀ¹ÌºÓ·1ºÅ +// if ("ÊÇ".equals(map.get("countyGov")) && "Å©".equals(map.get("verifyFlag"))) { +// basicModel.setResult(result); +// mav.setModel(basicModel); +// return mav; +// } +// //³ÇÊв»Ò»Ñù ÓÃÎÒÃÇ +// if (result.containsKey("city")) { +// if ((!result.get("city").equals(map.get("city")) && StringUtils.isNotBlank(result.getString("city")))) { +// basicModel.setResult(result); +// } else { +// map.put("addrVerify", "µØÖ·ÓÐЧ"); +// map.put("typeName", areaMap.get(map.get("typeCode"))); +// map.put("addrArea", addrArea(map, type)); +// map.put("countyLevelCity", countyLevelCity(map)); +// basicModel.setResult(map); +// } +// } else { +// map.put("addrVerify", "µØÖ·ÓÐЧ"); +// map.put("typeName", areaMap.get(map.get("typeCode"))); +// map.put("addrArea", addrArea(map, type)); +// map.put("countyLevelCity", countyLevelCity(map)); +// basicModel.setResult(map); +// } +// +// } else { +// basicModel.setResult(result); +// } +// +// } else { +// basicModel.setResult(result); +// +// } +// +// } catch (Exception e) { +// e.printStackTrace(); +// basicModel.setResult(result); +// } +// +// } - //½á¹û±È½Ï£¬Èç¹ûɿũ½á¹û²»Ò»Ö - //µ÷ÓÃÆëÁº type £º1 ¶Ô¹« 0 ¶Ô˽ - //ÎÒÃÇ type £º1 ¶Ô˽ 2 ¶Ô¹² - String qltype = "2".equals(type) ? "1" : "0"; - Map map = senRequest(address, qltype); - // ɿũ½á¹û²»Ò»Ñù - if (!map.get("verifyFlag").equals(result.get("verifyFlag"))) { - //ÓÐÊÐϽ½¨ÖÆÕò, »òÕß³ÇÊв»Ò»Ñù ÓÃÎÒÃÇ - if (result.containsKey("city") && ("ÊÇ".equals(result.get("administrativeTowns")) || (!result.get("city").equals(map.get("city")) - && StringUtils.isNotBlank(result.getString("city"))))) { - basicModel.setResult(result); - } else { - if (("ÊÇ").equals(result.get("countyLevelCity"))) { - map.put("prefectureLevelCity", "·ñ"); - } else if (("·ñ").equals(result.get("countyLevelCity"))) { - map.put("prefectureLevelCity", "ÊÇ"); - } - map.put("addrVerify", "µØÖ·ÓÐЧ"); - if (result.containsKey("countyLevelCity")) { - map.put("countyLevelCity", result.getString("countyLevelCity")); - } - map.put("typeName", areaMap.get(map.get("typeCode"))); - basicModel.setResult(map); - } - } else { - basicModel.setResult(result); - } - - } else { - basicModel.setResult(result); - - } - - } catch (Exception e) { - e.printStackTrace(); - basicModel.setResult(result); - } - - } } mav.setModel(basicModel); } else { diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/HouseController.java b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/HouseController.java index f3548c9cc..8870454dc 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/HouseController.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/HouseController.java @@ -4,9 +4,11 @@ import com.fangjia.core.util.*; import com.fangjia.dal.FacetQuery; import com.fangjia.dal.FacetQueryResult; import com.fangjia.dal.QueryParam; +import com.fangjia.dal.SeawaterQuery; import com.fangjia.dal.common.DistrictKey; import com.fangjia.dal.common.ServerAreaData; import com.fangjia.dal.datastore.model.House; +import com.fangjia.dal.datastore.model.RentHouse; import com.fangjia.dal.mongo.model.DistrictFacilitys; import com.fangjia.dal.mongo.model.FangjiaOfficialAreaMap; import com.fangjia.dal.mongo.model.Metro; @@ -14,6 +16,7 @@ import com.fangjia.dal.mongo.model.StatsIndex; import com.fangjia.dal.seawater.dao.SeawaterDao; import com.fangjia.dal.seawater.model.Seawater; import com.fangjia.dal.seaweed.model.District; +import com.fangjia.dal.seaweed.model.Seaweed; import com.fangjia.dal.sql.model.ApiUser; import com.fangjia.datastore.driver.FacetResult; import com.fangjia.open.FangjiaApiUtil; @@ -24,10 +27,7 @@ import com.fangjia.open.dto.UniversalDto; import com.fangjia.open.dto.addressGovernance.MatchedBuildingDto; import com.fangjia.open.interceptors.Authority; import com.fangjia.open.interceptors.Role; -import com.fangjia.open.model.BasicModel; -import com.fangjia.open.model.HousePublishModel; -import com.fangjia.open.model.HouseSearchModel; -import com.fangjia.open.model.RestfulModelAndView; +import com.fangjia.open.model.*; import com.fangjia.open.util.CommonDtoUtils; import com.fangjia.open.util.FileDao; import com.fangjia.open.ws.query.CollateralSampleQuery; @@ -38,10 +38,7 @@ import com.fangjia.service.bo.Collateral; import com.fangjia.service.bo.DistrictStatBo; import com.fangjia.service.bo.Sample; import com.fangjia.service.bo.ShopSample; -import com.fangjia.service.datastore.CzbankSampleService; -import com.fangjia.service.datastore.DistrictService; -import com.fangjia.service.datastore.HouseService; -import com.fangjia.service.datastore.NoHouseDistrictService; +import com.fangjia.service.datastore.*; import com.fangjia.service.datastore.bean.CollateralSampleQueryBean; import com.fangjia.service.datastore.bean.ShopCollateralSampleQueryBean; import com.fangjia.service.district.DistrictFacilitysService; @@ -63,340 +60,348 @@ import net.sf.json.JSONObject; import org.apache.commons.lang.StringUtils; import org.bson.types.ObjectId; import org.sothis.core.util.Closure; +import org.sothis.core.util.Pager; import org.springframework.web.multipart.MultipartFile; import javax.validation.Valid; import java.io.IOException; +import java.math.BigDecimal; +import java.text.SimpleDateFormat; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; + @Authority(role = Role.USER) public class HouseController { - private AddressParser addressParser; - private HouseService houseService; - private MenuService menuService; - private NoHouseDistrictService noHouseDistrictService; - private ApiUserService apiUserService; - private UserService userService; - private DistrictStatService districtStatService; - private DistrictFacilitysService districtFacilitysService; - private MetroService metroService; - private StatsIndexService statsIndexService; - private static final int HOUSE_DELETE_STATUS = 1; - private static long MAX_PIC_SIZE = 2 * 1024 * 1024; - private FileDao fileDao = FileDao.getInstance(); - public static final Map ESTATE_TYPE_CODE = new HashMap(); - public static final Map BULIDS_TYPE_CODE = new HashMap(); - public static final Map DIRECTION_CODE = new HashMap(); - public static final Map FITMENT_CODE = new HashMap(); - private static final Map STATS_INDEX_LATEST_DATE_CACHE = new HashMap(); - private static String CACHE_REFRESH_FLAG = null; - private CzbankSampleService czbankSampleService; - private DistrictService districtService; - private FangjiaOfficialAreaService fangjiaOfficialAreaService; + private AddressParser addressParser; + private HouseService houseService; - private SeawaterService seawaterService; - private SeawaterDao seawaterDao; - private List PROPERTY_TYPE_CODE_LIST = Arrays.asList("01", "02"); + private RentHouseService rentHouseService; + private MenuService menuService; + private NoHouseDistrictService noHouseDistrictService; + private ApiUserService apiUserService; + private UserService userService; + private DistrictStatService districtStatService; + private DistrictFacilitysService districtFacilitysService; + private MetroService metroService; + private StatsIndexService statsIndexService; + private static final int HOUSE_DELETE_STATUS = 1; + private static long MAX_PIC_SIZE = 2 * 1024 * 1024; + private FileDao fileDao = FileDao.getInstance(); + public static final Map ESTATE_TYPE_CODE = new HashMap(); + public static final Map BULIDS_TYPE_CODE = new HashMap(); + public static final Map DIRECTION_CODE = new HashMap(); + public static final Map FITMENT_CODE = new HashMap(); + private static final Map STATS_INDEX_LATEST_DATE_CACHE = new HashMap(); + private static String CACHE_REFRESH_FLAG = null; + private CzbankSampleService czbankSampleService; + private DistrictService districtService; + private FangjiaOfficialAreaService fangjiaOfficialAreaService; + + private SeawaterService seawaterService; + private SeawaterDao seawaterDao; + + private SeaweedService seaweedService; + private List PROPERTY_TYPE_CODE_LIST = Arrays.asList("01", "02"); - static { - ESTATE_TYPE_CODE.put("ÆÕͨסլ", "1"); - ESTATE_TYPE_CODE.put("±ðÊû", "2"); - ESTATE_TYPE_CODE.put("ÉÌס", "3"); + static { + ESTATE_TYPE_CODE.put("ÆÕͨסլ", "1"); + ESTATE_TYPE_CODE.put("±ðÊû", "2"); + ESTATE_TYPE_CODE.put("ÉÌס", "3"); - BULIDS_TYPE_CODE.put("¶à²ã", "10"); - BULIDS_TYPE_CODE.put("С¸ß²ã", "11"); - BULIDS_TYPE_CODE.put("³¬¸ß²ã", "12"); - BULIDS_TYPE_CODE.put("¸ß²ã", "13"); - BULIDS_TYPE_CODE.put("»¨Ô°Ñó·¿", "14"); - BULIDS_TYPE_CODE.put("ÀÏÑó·¿", "15"); - BULIDS_TYPE_CODE.put("ËĺÏÔº", "16"); - BULIDS_TYPE_CODE.put("¶À¶°", "17"); - BULIDS_TYPE_CODE.put("˫ƴ", "18"); - BULIDS_TYPE_CODE.put("ÁªÅÅ", "19"); - BULIDS_TYPE_CODE.put("µþ¼Ó", "20"); + BULIDS_TYPE_CODE.put("¶à²ã", "10"); + BULIDS_TYPE_CODE.put("С¸ß²ã", "11"); + BULIDS_TYPE_CODE.put("³¬¸ß²ã", "12"); + BULIDS_TYPE_CODE.put("¸ß²ã", "13"); + BULIDS_TYPE_CODE.put("»¨Ô°Ñó·¿", "14"); + BULIDS_TYPE_CODE.put("ÀÏÑó·¿", "15"); + BULIDS_TYPE_CODE.put("ËĺÏÔº", "16"); + BULIDS_TYPE_CODE.put("¶À¶°", "17"); + BULIDS_TYPE_CODE.put("˫ƴ", "18"); + BULIDS_TYPE_CODE.put("ÁªÅÅ", "19"); + BULIDS_TYPE_CODE.put("µþ¼Ó", "20"); - DIRECTION_CODE.put("Î÷±±", "1"); - DIRECTION_CODE.put("±±", "1"); - DIRECTION_CODE.put("¶«", "2"); - DIRECTION_CODE.put("Î÷", "2"); - DIRECTION_CODE.put("¶«Î÷", "2"); - DIRECTION_CODE.put("ÄÏ", "3"); - DIRECTION_CODE.put("¶«ÄÏ", "3"); - DIRECTION_CODE.put("Äϱ±", "3"); - DIRECTION_CODE.put("¶«±±", "4"); - DIRECTION_CODE.put("Î÷ÄÏ", "5"); + DIRECTION_CODE.put("Î÷±±", "1"); + DIRECTION_CODE.put("±±", "1"); + DIRECTION_CODE.put("¶«", "2"); + DIRECTION_CODE.put("Î÷", "2"); + DIRECTION_CODE.put("¶«Î÷", "2"); + DIRECTION_CODE.put("ÄÏ", "3"); + DIRECTION_CODE.put("¶«ÄÏ", "3"); + DIRECTION_CODE.put("Äϱ±", "3"); + DIRECTION_CODE.put("¶«±±", "4"); + DIRECTION_CODE.put("Î÷ÄÏ", "5"); - FITMENT_CODE.put("ëÅ÷", "1"); - FITMENT_CODE.put("¼ò×°", "1"); - FITMENT_CODE.put("¾«×°", "2"); - FITMENT_CODE.put("ȫװÐÞ", "3"); + FITMENT_CODE.put("ëÅ÷", "1"); + FITMENT_CODE.put("¼ò×°", "1"); + FITMENT_CODE.put("¾«×°", "2"); + FITMENT_CODE.put("ȫװÐÞ", "3"); - } + } - public static final String[] INCLUDE_DISTRICT_FIELDS = { - "id", "city", "region", "name", "address","estateType2", "alias", - "estateCharge", "virescencePercent", "cubagePercent", - "houseProperty","buildType","lat","lng","lat2","lng2", - "buildDate","finishBuildingDate","liveDate","propertyLife","block","openDate" - }; + public static final String[] INCLUDE_DISTRICT_FIELDS = { + "id", "city", "region", "name", "address", "estateType2", "alias", + "estateCharge", "virescencePercent", "cubagePercent", + "houseProperty", "buildType", "lat", "lng", "lat2", "lng2", + "buildDate", "finishBuildingDate", "liveDate", "propertyLife", "block", "openDate" + }; - private static final String[] INCLUDE_HOUSE_FIELDS = { - "id", "room", "hall", "toilet", "totalPrice", "area", "region", - "block", "city", "estateType", "direction", "height", "fitment", "floor", "districtName", - "address", "publishDate", "url"}; + private static final String[] INCLUDE_HOUSE_FIELDS = { + "id", "room", "hall", "toilet", "totalPrice", "area", "region", + "block", "city", "estateType", "direction", "height", "fitment", "floor", "districtName", + "address", "publishDate", "url"}; + public Object publishAction(@Valid HousePublishModel model) { + + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (model.getImage() == null || model.getImage().length == 0) { + mav.setModel(BasicModel.buildBadRequestModel("ͼƬ²»ÄÜΪ¿Õ")); + return mav; + } + MultipartFile[] images = model.getImage(); + for (int i = 0; i < images.length; i++) { + MultipartFile img = images[i]; + if (img.getSize() > MAX_PIC_SIZE) { + mav.setModel(BasicModel.buildBadRequestModel("ͼƬ¹ý´ó")); + return mav; + } + } + + Map tokenMap = FangjiaApiUtil.parseToken(model.getToken()); + String userId = tokenMap.get("userid"); + House house = createHouse(model, Integer.valueOf(userId)); + if (StringUtils.isNotBlank(house.getId())) { + if (StringUtils.isBlank(model.getId()) || !ObjectId.isValid(model.getId())) { + mav.setModel(BasicModel.buildBadRequestModel("·¿Ô´id²»ºÏ·¨")); + return mav; + } + House dbHouse = houseService.findHouseById(model.getId()); + if (dbHouse == null) { + mav.setModel(BasicModel.buildBadRequestModel("·¿Ô´²»´æÔÚ")); + return mav; + } + if (!userId.equals(dbHouse.getUserId().toString())) { + mav.setModel(BasicModel.buildUnAuthorizedModel().setMsg("ÄãûÓÐȨÏÞÐ޸ĸ÷¿Ô´")); + return mav; + } + for (String pic : dbHouse.getPics()) {//ɾ³ý¹ýʱµÄ·¿Ô´Í¼Æ¬ + fileDao.delete(pic, "user_house", "o"); + fileDao.delete(pic, "user_house", "s"); + fileDao.delete(pic, "user_house", "m"); + } + } + houseService.saveHouse(house); + List urls = new ArrayList(); + for (int i = 0; i < images.length && i < 8; i++) { + MultipartFile img = images[i]; + try { + String url = userId + "/" + house.getId() + "/api/" + img.getOriginalFilename(); + url = getPicUrl(url, urls); + fileDao.save(url, "user_house", "o", img.getBytes(), img.getContentType()); + fileDao.save(url, "user_house", "s", img.getBytes(), img.getContentType()); + fileDao.save(url, "user_house", "m", img.getBytes(), img.getContentType()); + } catch (IOException e) { + e.printStackTrace(); + } + } + house.setPics(urls); + houseService.updateUserHousePics(urls, house.getId(), Integer.valueOf(userId), "api"); + mav.setModel(BasicModel.buildOKModel().setResult(new HouseDto(house))); + return mav; + + } + + @Authority(role = Role.USER) + public Object similarAction(@Valid CollateralSampleQuery collateralSampleQuery) { + + RestfulModelAndView mav = new RestfulModelAndView(); + List querys = null; + try { + querys = convertQueryToBean(collateralSampleQuery); + } catch (Exception e) { + mav.setModel(BasicModel.buildBadRequestModel(e.getMessage())); + return mav; + } + if (null == collateralSampleQuery.getMax()) { + collateralSampleQuery.setMax(3); + } + List collaterals = czbankSampleService.findSample(querys, collateralSampleQuery.getMax()); + Collateral collateral = collaterals.get(0); + for (Sample sample : collateral.getSample()) { + if (querys.size() > 0 && querys.get(0).getProperty() != null) { + District district = querys.get(0).getProperty(); + if (district != null) { + sample.setHouseUseLimit(DataUtil.extractPrice(district.getPropertyLife())); + if (sample.getHouseUseLimit() == null && !Arrays.asList("³É¶¼", "ÖØÇì").contains(district.getCity())) { + if (district.getEstateType2() != null && district.getEstateType2().contains("ÉÌס")) { + sample.setHouseUseLimit(50); + } else { + sample.setHouseUseLimit(70); + } + } + if (sample.getHouseUseLimit() != null && sample.getCompleteDate() != null) { + Integer houseHadUsed = DateUtil.getYear(new Date()) - Integer.valueOf(sample.getCompleteDate().substring(0, 4)); + sample.setHouseHadUsed(houseHadUsed); + sample.setBuildingRemainLife(sample.getHouseUseLimit() - sample.getHouseHadUsed()); + } else { + sample.setHouseHadUsed(null); + sample.setBuildingRemainLife(null); + } + } + } + } + mav.setModel(BasicModel.buildOKModel().setResult(collateral.getSample())); + return mav; + } - public Object publishAction(@Valid HousePublishModel model){ - - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if(model.getImage() == null || model.getImage().length == 0){ - mav.setModel(BasicModel.buildBadRequestModel("ͼƬ²»ÄÜΪ¿Õ")); - return mav; - } - MultipartFile[] images = model.getImage(); - for (int i = 0; i < images.length; i++) { - MultipartFile img = images[i]; - if(img.getSize() > MAX_PIC_SIZE){ - mav.setModel(BasicModel.buildBadRequestModel("ͼƬ¹ý´ó")); - return mav; - } - } - - Map tokenMap = FangjiaApiUtil.parseToken(model.getToken()); - String userId = tokenMap.get("userid"); - House house = createHouse(model,Integer.valueOf(userId)); - if(StringUtils.isNotBlank(house.getId())){ - if(StringUtils.isBlank(model.getId()) || !ObjectId.isValid(model.getId())){ - mav.setModel(BasicModel.buildBadRequestModel("·¿Ô´id²»ºÏ·¨")); - return mav; - } - House dbHouse = houseService.findHouseById(model.getId()); - if(dbHouse == null){ - mav.setModel(BasicModel.buildBadRequestModel("·¿Ô´²»´æÔÚ")); - return mav; - } - if(!userId.equals(dbHouse.getUserId().toString())){ - mav.setModel(BasicModel.buildUnAuthorizedModel().setMsg("ÄãûÓÐȨÏÞÐ޸ĸ÷¿Ô´")); - return mav; - } - for(String pic : dbHouse.getPics()){//ɾ³ý¹ýʱµÄ·¿Ô´Í¼Æ¬ - fileDao.delete(pic,"user_house","o"); - fileDao.delete(pic,"user_house","s"); - fileDao.delete(pic,"user_house","m"); - } - } - houseService.saveHouse(house); - List urls = new ArrayList(); - for (int i = 0; i < images.length && i < 8; i++) { - MultipartFile img = images[i]; - try { - String url = userId + "/" + house.getId() + "/api/" + img.getOriginalFilename(); - url = getPicUrl(url,urls); - fileDao.save(url, "user_house", "o" ,img.getBytes(),img.getContentType()); - fileDao.save(url, "user_house", "s" ,img.getBytes(),img.getContentType()); - fileDao.save(url, "user_house", "m" ,img.getBytes(),img.getContentType()); - } catch (IOException e) { - e.printStackTrace(); - } - } - house.setPics(urls); - houseService.updateUserHousePics(urls, house.getId(), Integer.valueOf(userId), "api"); - mav.setModel(BasicModel.buildOKModel().setResult(new HouseDto(house))); - return mav; - - } - - @Authority(role = Role.USER) - public Object similarAction(@Valid CollateralSampleQuery collateralSampleQuery){ - - RestfulModelAndView mav = new RestfulModelAndView(); - List querys = null; - try{ - querys = convertQueryToBean(collateralSampleQuery); - }catch (Exception e){ - mav.setModel(BasicModel.buildBadRequestModel(e.getMessage())); - return mav; - } - if(null == collateralSampleQuery.getMax()){ - collateralSampleQuery.setMax(3); - } - List collaterals = czbankSampleService.findSample(querys, collateralSampleQuery.getMax()); - Collateral collateral = collaterals.get(0); - for(Sample sample : collateral.getSample()){ - if(querys.size() > 0 && querys.get(0).getProperty() != null){ - District district = querys.get(0).getProperty(); - if(district != null){ - sample.setHouseUseLimit(DataUtil.extractPrice(district.getPropertyLife())); - if(sample.getHouseUseLimit() == null && !Arrays.asList("³É¶¼", "ÖØÇì").contains(district.getCity())){ - if(district.getEstateType2() != null && district.getEstateType2().contains("ÉÌס")){ - sample.setHouseUseLimit(50); - }else{ - sample.setHouseUseLimit(70); - } - } - if(sample.getHouseUseLimit() != null && sample.getCompleteDate() != null){ - Integer houseHadUsed = DateUtil.getYear(new Date()) - Integer.valueOf(sample.getCompleteDate().substring(0, 4)); - sample.setHouseHadUsed(houseHadUsed); - sample.setBuildingRemainLife(sample.getHouseUseLimit() - sample.getHouseHadUsed()); - }else { - sample.setHouseHadUsed(null); - sample.setBuildingRemainLife(null); - } - } - } - } - mav.setModel(BasicModel.buildOKModel().setResult(collateral.getSample())); - return mav; - } + /** + * ÉÌÆÌÏàËÆ·¿Ô´½Ó¿Ú + */ + @Authority(role = Role.USER) + public Object shopSimilarAction(@Valid ShopCollateralSampleQuery query) { + RestfulModelAndView mav = new RestfulModelAndView(); + ShopCollateralSampleQueryBean queryBean = new ShopCollateralSampleQueryBean(); + BeanUtils.copyProperties(query, queryBean); + FangjiaOfficialAreaMap fangjiaOfficialAreaMap = fangjiaOfficialAreaService.convertOfficialCodeToFangjia(queryBean.getDistrict()); + if (fangjiaOfficialAreaMap == null) { + String msg = "µØÇøÐÅÏ¢ÎÞ·¨Ó³Éäµ½·¿¼ÛÍøµÄµØÇøÐÅÏ¢->(province:" + queryBean.getProvince() + " ,city: " + queryBean.getCity() + " ,district: " + queryBean.getDistrict() + ")"; + mav.setModel(BasicModel.buildBadRequestModel(msg)); + return mav; + } + queryBean.setFangjiaCity(fangjiaOfficialAreaMap.getFangjiaCity()); + queryBean.setFangjiaDistrict(fangjiaOfficialAreaMap.getFangjiaDistrict()); + District property = districtService.findByNameAndAlias(queryBean.getFangjiaCity(), queryBean.getFangjiaDistrict(), queryBean.getBuildingName(), "shop"); + if (property == null) { + mav.setModel(BasicModel.buildBadRequestModel("δÕÒµ½¸ÃÉÌÆÌ")); + return mav; + } + queryBean.setProperty(property); + List samples = czbankSampleService.findShopSample(queryBean, query.getMax()); + mav.setModel(BasicModel.buildOKModel().setResult(samples)); + return mav; + } - /**ÉÌÆÌÏàËÆ·¿Ô´½Ó¿Ú*/ - @Authority(role = Role.USER) - public Object shopSimilarAction(@Valid ShopCollateralSampleQuery query){ - RestfulModelAndView mav = new RestfulModelAndView(); - ShopCollateralSampleQueryBean queryBean = new ShopCollateralSampleQueryBean(); - BeanUtils.copyProperties(query, queryBean); - FangjiaOfficialAreaMap fangjiaOfficialAreaMap = fangjiaOfficialAreaService.convertOfficialCodeToFangjia(queryBean.getDistrict()); - if(fangjiaOfficialAreaMap == null){ - String msg = "µØÇøÐÅÏ¢ÎÞ·¨Ó³Éäµ½·¿¼ÛÍøµÄµØÇøÐÅÏ¢->(province:" + queryBean.getProvince() + " ,city: " + queryBean.getCity() + " ,district: " + queryBean.getDistrict() + ")"; - mav.setModel(BasicModel.buildBadRequestModel(msg)); - return mav; - } - queryBean.setFangjiaCity(fangjiaOfficialAreaMap.getFangjiaCity()); - queryBean.setFangjiaDistrict(fangjiaOfficialAreaMap.getFangjiaDistrict()); - District property = districtService.findByNameAndAlias(queryBean.getFangjiaCity(), queryBean.getFangjiaDistrict(), queryBean.getBuildingName(), "shop"); - if(property == null){ - mav.setModel(BasicModel.buildBadRequestModel("δÕÒµ½¸ÃÉÌÆÌ")); - return mav; - } - queryBean.setProperty(property); - List samples = czbankSampleService.findShopSample(queryBean, query.getMax()); - mav.setModel(BasicModel.buildOKModel().setResult(samples)); - return mav; - } + private List convertQueryToBean(CollateralSampleQuery... queries) throws Exception { + + List queryBeans = new ArrayList(queries.length); + for (CollateralSampleQuery q : queries) { + + CollateralSampleQueryBean queryBean = new CollateralSampleQueryBean(); + BeanUtils.copyProperties(q, queryBean); + String city = queryBean.getCity(); + FangjiaOfficialAreaMap fangjiaOfficialAreaMap = fangjiaOfficialAreaService.convertOfficialCodeToFangjia(q.getDistrict()); + if (fangjiaOfficialAreaMap == null) { + throw new Exception("µØÇøÐÅÏ¢ÎÞ·¨Ó³Éäµ½·¿¼ÛÍøµÄµØÇøÐÅÏ¢->(province:" + q.getProvince() + " ,city: " + q.getCity() + " ,district: " + q.getDistrict() + ")"); + } + queryBean.setFangjiaCity(fangjiaOfficialAreaMap.getFangjiaCity()); + queryBean.setFangjiaDistrict(fangjiaOfficialAreaMap.getFangjiaDistrict()); + + String propertyTypeCode = queryBean.getPropertyTypeCode(); + if (!PROPERTY_TYPE_CODE_LIST.contains(propertyTypeCode)) { + throw new Exception("propertyTypeCodeȡֵ·Ç·¨"); + } + String cat = "district"; + District property = districtService.findByNameAndAlias(queryBean.getFangjiaCity(), queryBean.getFangjiaDistrict(), queryBean.getBuildingName(), cat); + if (property == null) { + throw new Exception("δÕÒµ½¸ÃÐ¡Çø"); + } + queryBean.setProperty(property); + Integer decrCondCode = queryBean.getDecrCondCode(); + if (decrCondCode == null) { + decrCondCode = 2; + } + if (decrCondCode > 5 || decrCondCode < 1) { + throw new Exception("decrCondCodeȡֵ·Ç·¨"); + } + Integer towardDirectCode = queryBean.getTowardDirectCode(); + if (towardDirectCode == null) { + towardDirectCode = 3; + } + if (towardDirectCode > 10 || towardDirectCode < 1) { + throw new Exception("towardDirectCodeȡֵ·Ç·¨"); + } + queryBeans.add(queryBean); + } + return queryBeans; + } - private List convertQueryToBean(CollateralSampleQuery... queries) throws Exception{ + private List convertSampileQueryToBean(SampleQuery... queries) throws Exception { - List queryBeans = new ArrayList(queries.length); - for(CollateralSampleQuery q : queries){ + List queryBeans = new ArrayList(queries.length); + for (SampleQuery q : queries) { - CollateralSampleQueryBean queryBean = new CollateralSampleQueryBean(); - BeanUtils.copyProperties(q, queryBean); - String city = queryBean.getCity(); - FangjiaOfficialAreaMap fangjiaOfficialAreaMap = fangjiaOfficialAreaService.convertOfficialCodeToFangjia(q.getDistrict()); - if(fangjiaOfficialAreaMap == null){ - throw new Exception("µØÇøÐÅÏ¢ÎÞ·¨Ó³Éäµ½·¿¼ÛÍøµÄµØÇøÐÅÏ¢->(province:" + q.getProvince() + " ,city: " + q.getCity() + " ,district: " + q.getDistrict() + ")"); - } - queryBean.setFangjiaCity(fangjiaOfficialAreaMap.getFangjiaCity()); - queryBean.setFangjiaDistrict(fangjiaOfficialAreaMap.getFangjiaDistrict()); - - String propertyTypeCode = queryBean.getPropertyTypeCode(); - if(!PROPERTY_TYPE_CODE_LIST.contains(propertyTypeCode)){ - throw new Exception("propertyTypeCodeȡֵ·Ç·¨"); - } - String cat = "district"; - District property = districtService.findByNameAndAlias(queryBean.getFangjiaCity(), queryBean.getFangjiaDistrict(), queryBean.getBuildingName(), cat); - if(property == null){ - throw new Exception("δÕÒµ½¸ÃÐ¡Çø"); - } - queryBean.setProperty(property); - Integer decrCondCode = queryBean.getDecrCondCode(); - if(decrCondCode == null){ - decrCondCode = 2; - } - if(decrCondCode > 5 || decrCondCode < 1){ - throw new Exception("decrCondCodeȡֵ·Ç·¨"); - } - Integer towardDirectCode = queryBean.getTowardDirectCode(); - if(towardDirectCode == null){ - towardDirectCode = 3; - } - if(towardDirectCode > 10 || towardDirectCode < 1){ - throw new Exception("towardDirectCodeȡֵ·Ç·¨"); - } - queryBeans.add(queryBean); - } - return queryBeans; - } - - - private List convertSampileQueryToBean(SampleQuery... queries) throws Exception{ - - List queryBeans = new ArrayList(queries.length); - for(SampleQuery q : queries){ - - CollateralSampleQueryBean queryBean = new CollateralSampleQueryBean(); - BeanUtils.copyProperties(q, queryBean); + CollateralSampleQueryBean queryBean = new CollateralSampleQueryBean(); + BeanUtils.copyProperties(q, queryBean); // String propertyTypeCode = queryBean.getPropertyTypeCode(); // if(!Arrays.asList("01", "02", "03").contains(propertyTypeCode)){ // throw new Exception("propertyTypeCodeȡֵ·Ç·¨"); // } - String cat = "district"; + String cat = "district"; - if(StringUtils.isNotBlank(queryBean.getCity()) && StringUtils.isNotBlank(queryBean.getDistrict()) && StringUtils.isNotBlank(queryBean.getBuildingName())){ - District property = districtService.findByNameAndAlias(queryBean.getCity(), queryBean.getDistrict(), queryBean.getBuildingName(), cat); - if(property == null){ - throw new Exception("δÕÒµ½¸ÃÐ¡Çø"); - } - queryBean.setProperty(property); - }else if(StringUtils.isNotBlank(queryBean.getAddress())){ - HttpRequest request = new HttpRequest(); - JSONObject json = null; - String address = queryBean.getAddress().replace(" ","").replace("%",""); - Map params = new HashMap(); - params.put("city", queryBean.getCity()); - params.put("address", address); - params.put("category", "property"); - //ÐÂÆ¥Åä½Ó¿Ú - json = request.getJsonContent("http://192.168.0.100:32080/FangJiaNlpService/match", params, "UTF-8"); - if (json != null && json.size()>0) { - MatchedBuildingDto dto = CommonDtoUtils.transformV(MatchedBuildingDto.class, json); - District property = districtService.findByNameAndAlias(dto.getCity(), dto.getDistrict(), dto.getName(), cat); - if(property == null){ - throw new Exception("δÕÒµ½¸ÃÐ¡Çø"); - } - queryBean.setProperty(property); - }else{ - throw new Exception("δÕÒµ½¸ÃÐ¡Çø"); - } - } - String estateType = queryBean.getProperty().getEstateType2(); - queryBean.setPropertyTypeCode("01"); - if(StringUtils.isNotBlank(estateType)){ - if(estateType.equals("ÆÕͨסլ")){ - queryBean.setPropertyTypeCode("01"); - }else if(estateType.equals("±ðÊû")){ - queryBean.setPropertyTypeCode("02"); - }else if(estateType.equals("ÉÌס")){ - queryBean.setPropertyTypeCode("03"); - } - } + if (StringUtils.isNotBlank(queryBean.getCity()) && StringUtils.isNotBlank(queryBean.getDistrict()) && StringUtils.isNotBlank(queryBean.getBuildingName())) { + District property = districtService.findByNameAndAlias(queryBean.getCity(), queryBean.getDistrict(), queryBean.getBuildingName(), cat); + if (property == null) { + throw new Exception("δÕÒµ½¸ÃÐ¡Çø"); + } + queryBean.setProperty(property); + } else if (StringUtils.isNotBlank(queryBean.getAddress())) { + HttpRequest request = new HttpRequest(); + JSONObject json = null; + String address = queryBean.getAddress().replace(" ", "").replace("%", ""); + Map params = new HashMap(); + params.put("city", queryBean.getCity()); + params.put("address", address); + params.put("category", "property"); + //ÐÂÆ¥Åä½Ó¿Ú + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaNlpService/match", params, "UTF-8"); + if (json != null && json.size() > 0) { + MatchedBuildingDto dto = CommonDtoUtils.transformV(MatchedBuildingDto.class, json); + District property = districtService.findByNameAndAlias(dto.getCity(), dto.getDistrict(), dto.getName(), cat); + if (property == null) { + throw new Exception("δÕÒµ½¸ÃÐ¡Çø"); + } + queryBean.setProperty(property); + } else { + throw new Exception("δÕÒµ½¸ÃÐ¡Çø"); + } + } + String estateType = queryBean.getProperty().getEstateType2(); + queryBean.setPropertyTypeCode("01"); + if (StringUtils.isNotBlank(estateType)) { + if (estateType.equals("ÆÕͨסլ")) { + queryBean.setPropertyTypeCode("01"); + } else if (estateType.equals("±ðÊû")) { + queryBean.setPropertyTypeCode("02"); + } else if (estateType.equals("ÉÌס")) { + queryBean.setPropertyTypeCode("03"); + } + } - Integer decrCondCode = queryBean.getDecrCondCode(); - if(decrCondCode == null){ - decrCondCode = 2; - } - if(decrCondCode > 5 || decrCondCode < 1){ - throw new Exception("decrCondCodeȡֵ·Ç·¨"); - } - Integer towardDirectCode = queryBean.getTowardDirectCode(); - if(towardDirectCode == null){ - towardDirectCode = 3; - } - if(towardDirectCode > 10 || towardDirectCode < 1){ - throw new Exception("towardDirectCodeȡֵ·Ç·¨"); - } - queryBeans.add(queryBean); - } - return queryBeans; - } + Integer decrCondCode = queryBean.getDecrCondCode(); + if (decrCondCode == null) { + decrCondCode = 2; + } + if (decrCondCode > 5 || decrCondCode < 1) { + throw new Exception("decrCondCodeȡֵ·Ç·¨"); + } + Integer towardDirectCode = queryBean.getTowardDirectCode(); + if (towardDirectCode == null) { + towardDirectCode = 3; + } + if (towardDirectCode > 10 || towardDirectCode < 1) { + throw new Exception("towardDirectCodeȡֵ·Ç·¨"); + } + queryBeans.add(queryBean); + } + return queryBeans; + } // private List convertSampileQueryToBean(SampleQuery... queries) throws Exception{ @@ -437,487 +442,976 @@ public class HouseController { // return queryBeans; // } - public Object detailAction(HousePublishModel model){ - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if(StringUtils.isBlank(model.getId())){ - mav.setModel(BasicModel.buildBadRequestModel("·¿Ô´id²»ÄÜΪ¿Õ")); - return mav; - } - if(StringUtils.isBlank(model.getId()) || !ObjectId.isValid(model.getId())){ - mav.setModel(BasicModel.buildBadRequestModel("·¿Ô´id²»ºÏ·¨")); - return mav; - } - House dbHouse = houseService.findHouseById(model.getId()); - if(dbHouse == null || dbHouse.getStatus() == HOUSE_DELETE_STATUS){ - mav.setModel(BasicModel.buildBadRequestModel("·¿Ô´²»´æÔÚ")); - return mav; - } - Map tokenMap = FangjiaApiUtil.parseToken(model.getToken()); - String userId = tokenMap.get("userid"); - if(dbHouse.getUserId() == null || !userId.equals(dbHouse.getUserId().toString())){ - mav.setModel(BasicModel.buildUnAuthorizedModel().setMsg("ÄãûÓÐȨÏÞ·ÃÎʸ÷¿Ô´")); - return mav; - } - mav.setModel(BasicModel.buildOKModel().setResult(new HouseDto(dbHouse))); - return mav; - } + public Object detailAction(HousePublishModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isBlank(model.getId())) { + mav.setModel(BasicModel.buildBadRequestModel("·¿Ô´id²»ÄÜΪ¿Õ")); + return mav; + } + if (StringUtils.isBlank(model.getId()) || !ObjectId.isValid(model.getId())) { + mav.setModel(BasicModel.buildBadRequestModel("·¿Ô´id²»ºÏ·¨")); + return mav; + } + House dbHouse = houseService.findHouseById(model.getId()); + if (dbHouse == null || dbHouse.getStatus() == HOUSE_DELETE_STATUS) { + mav.setModel(BasicModel.buildBadRequestModel("·¿Ô´²»´æÔÚ")); + return mav; + } + Map tokenMap = FangjiaApiUtil.parseToken(model.getToken()); + String userId = tokenMap.get("userid"); + if (dbHouse.getUserId() == null || !userId.equals(dbHouse.getUserId().toString())) { + mav.setModel(BasicModel.buildUnAuthorizedModel().setMsg("ÄãûÓÐȨÏÞ·ÃÎʸ÷¿Ô´")); + return mav; + } + mav.setModel(BasicModel.buildOKModel().setResult(new HouseDto(dbHouse))); + return mav; + } - public Object deleteAction(HousePublishModel model){ - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if(StringUtils.isBlank(model.getId())){ - mav.setModel(BasicModel.buildBadRequestModel("·¿Ô´id²»ÄÜΪ¿Õ")); - return mav; - } - if(StringUtils.isBlank(model.getId()) || !ObjectId.isValid(model.getId())){ - mav.setModel(BasicModel.buildBadRequestModel("·¿Ô´id²»ºÏ·¨")); - return mav; - } - House dbHouse = houseService.findHouseById(model.getId()); - if(dbHouse == null || dbHouse.getStatus() == HOUSE_DELETE_STATUS){ - mav.setModel(BasicModel.buildBadRequestModel("·¿Ô´²»´æÔÚ")); - return mav; - } - Map tokenMap = FangjiaApiUtil.parseToken(model.getToken()); - String userId = tokenMap.get("userid"); - if(dbHouse.getUserId() == null || !userId.equals(dbHouse.getUserId().toString())){ - mav.setModel(BasicModel.buildUnAuthorizedModel().setMsg("ÄãûÓÐȨÏÞɾ³ý¸Ã·¿Ô´")); - return mav; - } - houseService.deleteHouse(dbHouse.getId()); - mav.setModel(BasicModel.buildOKModel().setMsg("ɾ³ý³É¹¦")); - return mav; - } + public Object deleteAction(HousePublishModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isBlank(model.getId())) { + mav.setModel(BasicModel.buildBadRequestModel("·¿Ô´id²»ÄÜΪ¿Õ")); + return mav; + } + if (StringUtils.isBlank(model.getId()) || !ObjectId.isValid(model.getId())) { + mav.setModel(BasicModel.buildBadRequestModel("·¿Ô´id²»ºÏ·¨")); + return mav; + } + House dbHouse = houseService.findHouseById(model.getId()); + if (dbHouse == null || dbHouse.getStatus() == HOUSE_DELETE_STATUS) { + mav.setModel(BasicModel.buildBadRequestModel("·¿Ô´²»´æÔÚ")); + return mav; + } + Map tokenMap = FangjiaApiUtil.parseToken(model.getToken()); + String userId = tokenMap.get("userid"); + if (dbHouse.getUserId() == null || !userId.equals(dbHouse.getUserId().toString())) { + mav.setModel(BasicModel.buildUnAuthorizedModel().setMsg("ÄãûÓÐȨÏÞɾ³ý¸Ã·¿Ô´")); + return mav; + } + houseService.deleteHouse(dbHouse.getId()); + mav.setModel(BasicModel.buildOKModel().setMsg("ɾ³ý³É¹¦")); + return mav; + } - public Object refreshAction(HousePublishModel model){ - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if(StringUtils.isBlank(model.getId())){ - mav.setModel(BasicModel.buildBadRequestModel("·¿Ô´id²»ÄÜΪ¿Õ")); - return mav; - } - if(StringUtils.isBlank(model.getId()) || !ObjectId.isValid(model.getId())){ - mav.setModel(BasicModel.buildBadRequestModel("·¿Ô´id²»ºÏ·¨")); - return mav; - } - House dbHouse = houseService.findHouseById(model.getId()); - if(dbHouse == null || dbHouse.getStatus() == HOUSE_DELETE_STATUS){ - mav.setModel(BasicModel.buildBadRequestModel("·¿Ô´²»´æÔÚ")); - return mav; - } - Map tokenMap = FangjiaApiUtil.parseToken(model.getToken()); - String userId = tokenMap.get("userid"); - if(dbHouse.getUserId() == null || !userId.equals(dbHouse.getUserId().toString())){ - mav.setModel(BasicModel.buildUnAuthorizedModel().setMsg("ÄãûÓÐȨÏÞɾ³ý¸Ã·¿Ô´")); - return mav; - } - boolean refresh = houseService.refreshHouse(dbHouse.getId(), Integer.valueOf(userId), "api"); - if(!refresh){ - mav.setModel(BasicModel.buildOKModel().setMsg("ÿÌìÖ»ÄÜË¢ÐÂÒ»´Î·¿Ô´")); - return mav; - }else{ - mav.setModel(BasicModel.buildOKModel().setMsg("ˢгɹ¦")); - return mav; - } - } + public Object refreshAction(HousePublishModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isBlank(model.getId())) { + mav.setModel(BasicModel.buildBadRequestModel("·¿Ô´id²»ÄÜΪ¿Õ")); + return mav; + } + if (StringUtils.isBlank(model.getId()) || !ObjectId.isValid(model.getId())) { + mav.setModel(BasicModel.buildBadRequestModel("·¿Ô´id²»ºÏ·¨")); + return mav; + } + House dbHouse = houseService.findHouseById(model.getId()); + if (dbHouse == null || dbHouse.getStatus() == HOUSE_DELETE_STATUS) { + mav.setModel(BasicModel.buildBadRequestModel("·¿Ô´²»´æÔÚ")); + return mav; + } + Map tokenMap = FangjiaApiUtil.parseToken(model.getToken()); + String userId = tokenMap.get("userid"); + if (dbHouse.getUserId() == null || !userId.equals(dbHouse.getUserId().toString())) { + mav.setModel(BasicModel.buildUnAuthorizedModel().setMsg("ÄãûÓÐȨÏÞɾ³ý¸Ã·¿Ô´")); + return mav; + } + boolean refresh = houseService.refreshHouse(dbHouse.getId(), Integer.valueOf(userId), "api"); + if (!refresh) { + mav.setModel(BasicModel.buildOKModel().setMsg("ÿÌìÖ»ÄÜË¢ÐÂÒ»´Î·¿Ô´")); + return mav; + } else { + mav.setModel(BasicModel.buildOKModel().setMsg("ˢгɹ¦")); + return mav; + } + } - public Object listAction(final HouseSearchModel model) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if (StringUtils.isBlank(model.getId()) && (StringUtils.isBlank(model.getCity()) || StringUtils.isBlank(model.getRegion()) || StringUtils.isBlank(model.getName()))) { - mav.setModel(BasicModel.buildBadRequestModel("Â¥Å̱àºÅ»ò³ÇÊÐ,ÇøÓò£¬Ãû³ÆÎª±ØÌîÏî")); - return mav; - } - District district = null; - DistrictKey districtKey = null; - if(StringUtils.isNotBlank(model.getName())){ - districtKey = new DistrictKey(model.getCity(), model.getRegion(), model.getName()); - district = districtService.findDistrict(districtKey, "district"); - }else{ - district = districtService.findDistrictById(model.getId()); - if(district!=null){ - districtKey = new DistrictKey(district.getCity(), district.getRegion(), district.getName()); - } - } + public Object listAction(final HouseSearchModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isBlank(model.getId()) && (StringUtils.isBlank(model.getCity()) || StringUtils.isBlank(model.getRegion()) || StringUtils.isBlank(model.getName()))) { + mav.setModel(BasicModel.buildBadRequestModel("Â¥Å̱àºÅ»ò³ÇÊÐ,ÇøÓò£¬Ãû³ÆÎª±ØÌîÏî")); + return mav; + } + District district = null; + DistrictKey districtKey = null; + if (StringUtils.isNotBlank(model.getName())) { + districtKey = new DistrictKey(model.getCity(), model.getRegion(), model.getName()); + district = districtService.findDistrict(districtKey, "district"); + } else { + district = districtService.findDistrictById(model.getId()); + if (district != null) { + districtKey = new DistrictKey(district.getCity(), district.getRegion(), district.getName()); + } + } - if(district == null){ - mav.setModel(BasicModel.buildBadRequestModel("¸ÃÐ¡Çø²»´æÔÚ")); - return mav; - } - DistrictStatBo bo = districtStatService.findCurrentDistrictStat(districtKey); - Integer minPrice = null; - Integer maxPrice = null; - if(bo.getDistrictStat()!=null){ - minPrice = (int)(bo.getDistrictStat().getAvgPrice() * 0.8); - maxPrice = (int)(bo.getDistrictStat().getAvgPrice() * 1.2); - } - List names = new ArrayList(); - names.add(district.getName()); - if(district.getAlias() != null){ - for(String alia : district.getAlias()){ - if(StringUtils.isNotBlank(alia) && !names.contains(alia)){ - names.add(alia); - } - } - } - List houses = seawaterDao.findSeawatersFromEs("sell", district.getCity(), district.getRegion(), district.getName(), district.getAlias(), null, model.getStartTime(), model.getEndTime(),null,null,minPrice, maxPrice,null,null,"p_date", false,0, model.getPageSize(),"latest_seawater"); - //List houses1 = seawaterDao.findHouses(district.getCity(), district.getRegion(), names, minPrice, maxPrice, model.getPageSize()); - mav.setModel(BasicModel.buildOKModel().setResult(houses)); - return mav; - } + if (district == null) { + mav.setModel(BasicModel.buildBadRequestModel("¸ÃÐ¡Çø²»´æÔÚ")); + return mav; + } + DistrictStatBo bo = districtStatService.findCurrentDistrictStat(districtKey); + Integer minPrice = null; + Integer maxPrice = null; + if (bo.getDistrictStat() != null) { + minPrice = (int) (bo.getDistrictStat().getAvgPrice() * 0.8); + maxPrice = (int) (bo.getDistrictStat().getAvgPrice() * 1.2); + } + List names = new ArrayList(); + names.add(district.getName()); + if (district.getAlias() != null) { + for (String alia : district.getAlias()) { + if (StringUtils.isNotBlank(alia) && !names.contains(alia)) { + names.add(alia); + } + } + } + List houses = seawaterDao.findSeawatersFromEs("sell", district.getCity(), district.getRegion(), district.getName(), district.getAlias(), null, model.getStartTime(), model.getEndTime(), null, null, minPrice, maxPrice, null, null, "p_date", false, 0, model.getPageSize(), "latest_seawater"); + //List houses1 = seawaterDao.findHouses(district.getCity(), district.getRegion(), names, minPrice, maxPrice, model.getPageSize()); + mav.setModel(BasicModel.buildOKModel().setResult(houses)); + return mav; + } + public Object arroundlistAction(final HouseSearchModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isBlank(model.getId()) && (StringUtils.isBlank(model.getCity()) || StringUtils.isBlank(model.getRegion()) || StringUtils.isBlank(model.getName()))) { + mav.setModel(BasicModel.buildBadRequestModel("Â¥Å̱àºÅ»ò³ÇÊÐ,ÇøÓò£¬Ãû³ÆÎª±ØÌîÏî")); + return mav; + } + District district = null; + DistrictKey districtKey = null; + if (StringUtils.isNotBlank(model.getName())) { + districtKey = new DistrictKey(model.getCity(), model.getRegion(), model.getName()); + district = districtService.findDistrict(districtKey, "district"); + } else { + district = districtService.findDistrictById(model.getId()); + if (district != null) { + districtKey = new DistrictKey(district.getCity(), district.getRegion(), district.getName()); + } + } - public Object arroundlistAction(final HouseSearchModel model) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if (StringUtils.isBlank(model.getId()) && (StringUtils.isBlank(model.getCity()) || StringUtils.isBlank(model.getRegion()) || StringUtils.isBlank(model.getName()))) { - mav.setModel(BasicModel.buildBadRequestModel("Â¥Å̱àºÅ»ò³ÇÊÐ,ÇøÓò£¬Ãû³ÆÎª±ØÌîÏî")); - return mav; - } - District district = null; - DistrictKey districtKey = null; - if(StringUtils.isNotBlank(model.getName())){ - districtKey = new DistrictKey(model.getCity(), model.getRegion(), model.getName()); - district = districtService.findDistrict(districtKey, "district"); - }else{ - district = districtService.findDistrictById(model.getId()); - if(district!=null){ - districtKey = new DistrictKey(district.getCity(), district.getRegion(), district.getName()); - } - } + if (district == null) { + mav.setModel(BasicModel.buildBadRequestModel("¸ÃÐ¡Çø²»´æÔÚ")); + return mav; + } - if(district == null){ - mav.setModel(BasicModel.buildBadRequestModel("¸ÃÐ¡Çø²»´æÔÚ")); - return mav; - } + //ÖܱßÐ¡Çø£¬Ä¬ÈÏ10 + List districts = districtService.findNearestDistrict(district, 1000, model.getDistCount()); + List houses = new ArrayList(); + for (District dist : districts) { + districtKey = new DistrictKey(dist.getCity(), dist.getRegion(), dist.getName()); + DistrictStatBo bo = districtStatService.findCurrentDistrictStat(districtKey); + Integer minPrice = null; + Integer maxPrice = null; + if (bo.getDistrictStat() != null) { + minPrice = (int) (bo.getDistrictStat().getAvgPrice() * 0.9); + maxPrice = (int) (bo.getDistrictStat().getAvgPrice() * 1.1); + } + List names = new ArrayList(); + names.add(district.getName()); + if (district.getAlias() != null) { + for (String alia : district.getAlias()) { + if (StringUtils.isNotBlank(alia) && !names.contains(alia)) { + names.add(alia); + } + } + } + List arroundhouses = seawaterDao.findSeawatersFromEs("sell", dist.getCity(), dist.getRegion(), dist.getName(), dist.getAlias(), null, model.getStartTime(), model.getEndTime(), null, null, minPrice, maxPrice, null, null, "p_date", false, 0, model.getPageSize(), "latest_seawater"); + if (arroundhouses != null && arroundhouses.size() > 0) { + houses.addAll(arroundhouses); + } + } + mav.setModel(BasicModel.buildOKModel().setResult(houses)); + return mav; + } - //ÖܱßÐ¡Çø£¬Ä¬ÈÏ10 - List districts = districtService.findNearestDistrict(district, 1000, model.getDistCount()); - List houses = new ArrayList(); - for(District dist : districts){ - districtKey = new DistrictKey(dist.getCity(), dist.getRegion(), dist.getName()); - DistrictStatBo bo = districtStatService.findCurrentDistrictStat(districtKey); - Integer minPrice = null; - Integer maxPrice = null; - if(bo.getDistrictStat()!=null){ - minPrice = (int)(bo.getDistrictStat().getAvgPrice() * 0.9); - maxPrice = (int)(bo.getDistrictStat().getAvgPrice() * 1.1); - } - List names = new ArrayList(); - names.add(district.getName()); - if(district.getAlias() != null){ - for(String alia : district.getAlias()){ - if(StringUtils.isNotBlank(alia) && !names.contains(alia)){ - names.add(alia); - } - } - } - List arroundhouses = seawaterDao.findSeawatersFromEs("sell", dist.getCity(), dist.getRegion(), dist.getName(), dist.getAlias(), null, model.getStartTime(), model.getEndTime(),null,null,minPrice, maxPrice,null,null,"p_date", false,0, model.getPageSize(),"latest_seawater"); - if(arroundhouses!=null && arroundhouses.size()>0){ - houses.addAll(arroundhouses); - } - } - mav.setModel(BasicModel.buildOKModel().setResult(houses)); - return mav; - } + String getPicUrl(String url, List urls) { + if (!urls.contains(url)) { + urls.add(url); + return url; + } + for (int i = 0; ; i++) { + String newName = url + "_" + i; + if (!urls.contains(newName)) { + return url; + } + } + } - String getPicUrl(String url, List urls) { - if (!urls.contains(url)) { - urls.add(url); - return url; - } - for (int i = 0;; i++) { - String newName = url + "_" + i; - if (!urls.contains(newName)) { - return url; - } - } - } + private House createHouse(HousePublishModel model, Integer userId) { + House house = new House(); + house.setSource("api"); + house.setUserId(userId); + house.setCat("sell"); + house.setId(model.getId()); + house.setDistrictName(model.getPropertyName()); + house.setCity(model.getCity()); + house.setRegion(model.getDistrict()); + house.setBlock(model.getBlock()); + house.setAddress(model.getAddress()); + house.setName(model.getTitle()); + house.setDescription(model.getDescription()); + house.setBuildDate(model.getBuildDate() == null ? null : (model.getBuildDate().toString() + "Äê")); + house.setContactPeople(model.getContactPerson()); + house.setMobile(model.getMobile()); + house.setFloor(model.getFloor()); + house.setHeight(model.getMaxFloor()); + house.setFitment(model.getFitment()); + house.setDirection(model.getDirection()); + house.setTotalPrice((int) (model.getTotalPrice() * 10000)); + house.setArea(model.getSize()); + house.setRoom(model.getRoom()); + house.setHall(model.getHall()); + house.setToilet(model.getToilet()); + house.setHouseNum(model.getBuildingNum()); + house.setRoomNum(model.getRoomNum()); + house.setUrl("fangjia.com"); + house.setStatus(0); + house.setPublishDate(new Date()); + house.setModificationDate(new Date()); + house.setRemark(model.getRemark()); + return house; + } - private House createHouse(HousePublishModel model, Integer userId){ - House house = new House(); - house.setSource("api"); - house.setUserId(userId); - house.setCat("sell"); - house.setId(model.getId()); - house.setDistrictName(model.getPropertyName()); - house.setCity(model.getCity()); - house.setRegion(model.getDistrict()); - house.setBlock(model.getBlock()); - house.setAddress(model.getAddress()); - house.setName(model.getTitle()); - house.setDescription(model.getDescription()); - house.setBuildDate(model.getBuildDate() == null ? null : (model.getBuildDate().toString() + "Äê")); - house.setContactPeople(model.getContactPerson()); - house.setMobile(model.getMobile()); - house.setFloor(model.getFloor()); - house.setHeight(model.getMaxFloor()); - house.setFitment(model.getFitment()); - house.setDirection(model.getDirection()); - house.setTotalPrice((int)(model.getTotalPrice() * 10000)); - house.setArea(model.getSize()); - house.setRoom(model.getRoom()); - house.setHall(model.getHall()); - house.setToilet(model.getToilet()); - house.setHouseNum(model.getBuildingNum()); - house.setRoomNum(model.getRoomNum()); - house.setUrl("fangjia.com"); - house.setStatus(0); - house.setPublishDate(new Date()); - house.setModificationDate(new Date()); - house.setRemark(model.getRemark()); - return house; - } + @Authority(role = Role.USER) + public Object rankAction(final HouseSearchModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); - @Authority(role = Role.USER) - public Object rankAction(final HouseSearchModel model) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - - Map resMap = new LinkedHashMap(); - if(StringUtils.isBlank(model.getCity()) || model.getTotalPrice() == null) { - mav.setModel(BasicModel.buildBadRequestModel("±ØÌî²ÎÊý´íÎó")); - return mav; - }else { - double[] compArrs = compareTotalPrice(model.getCity(), model.getTotalPrice()); - if (compArrs == null) { - resMap.put("rank", 0); - } else { - resMap.put("rank", compArrs[0]); - } - resMap.put("totalPrice", model.getTotalPrice()); - resMap.put("city", model.getCity()); - } - mav.setModel(resMap); - return mav; - } + Map resMap = new LinkedHashMap(); + if (StringUtils.isBlank(model.getCity()) || model.getTotalPrice() == null) { + mav.setModel(BasicModel.buildBadRequestModel("±ØÌî²ÎÊý´íÎó")); + return mav; + } else { + double[] compArrs = compareTotalPrice(model.getCity(), model.getTotalPrice()); + if (compArrs == null) { + resMap.put("rank", 0); + } else { + resMap.put("rank", compArrs[0]); + } + resMap.put("totalPrice", model.getTotalPrice()); + resMap.put("city", model.getCity()); + } + mav.setModel(resMap); + return mav; + } - public static final int VALUE_SKIP = 100; - private double[] compareTotalPrice(String city, int totalPrice) { - if(StringUtils.isBlank(city) || totalPrice <= 1000) { - return null; - } + public static final int VALUE_SKIP = 100; - final FacetQuery facetQuery = new FacetQuery(); - facetQuery.setFields(Arrays.asList("totalPriceRange")); - facetQuery.setLimit(20); - facetQuery.setMinCount(1); - final List params = new ArrayList(); - params.add(new QueryParam("cat", "sell")); - params.add(new QueryParam("visible", 0)); - params.add(new QueryParam("city", city)); - List facetQueryResult = CacheUtils.getValue(this.getClass(), "totalPriceRange", city, CacheUtils.CachePolicyEnum.MIDDLE, new Closure, String>() { - @Override - public List execute(String input) { - return houseService.facetSearch(params, facetQuery); - } - }); + private double[] compareTotalPrice(String city, int totalPrice) { + if (StringUtils.isBlank(city) || totalPrice <= 1000) { + return null; + } - int totalCount = 0; - Map rangeMap = new HashMap(); - for(FacetResult ft : facetQueryResult) { - if("total_price_range".equals(ft.getName()) && ft.getValues() != null) { - for(FacetResult.Count c : ft.getValues()) { - rangeMap.put(c.getName(), (int)c.getCount()); - totalCount += c.getCount(); - } - } - } + final FacetQuery facetQuery = new FacetQuery(); + facetQuery.setFields(Arrays.asList("totalPriceRange")); + facetQuery.setLimit(20); + facetQuery.setMinCount(1); + final List params = new ArrayList(); + params.add(new QueryParam("cat", "sell")); + params.add(new QueryParam("visible", 0)); + params.add(new QueryParam("city", city)); + List facetQueryResult = CacheUtils.getValue(this.getClass(), "totalPriceRange", city, CacheUtils.CachePolicyEnum.MIDDLE, new Closure, String>() { + @Override + public List execute(String input) { + return houseService.facetSearch(params, facetQuery); + } + }); - int baseLessThan = 0; - int baseGreaterThan = 0; - Value inthisValue = null; + int totalCount = 0; + Map rangeMap = new HashMap(); + for (FacetResult ft : facetQueryResult) { + if ("total_price_range".equals(ft.getName()) && ft.getValues() != null) { + for (FacetResult.Count c : ft.getValues()) { + rangeMap.put(c.getName(), (int) c.getCount()); + totalCount += c.getCount(); + } + } + } - //·¿Ô´µÄ×î´ó×îСֵ - Integer[] extrmeValue = houseService.findExtremeTotalPrice(city, null); - if(extrmeValue == null) { - return null; - } + int baseLessThan = 0; + int baseGreaterThan = 0; + Value inthisValue = null; - List items = menuService.getItems(ServerAreaData.getServerAreaByDisplay(city), MenuCategoryEnum.ershoufang, "totalPriceRange"); - for(Item item : items) { - String[] vals = item.getValue().split("_"); - if (vals == null || vals.length == 0) { - continue; - } + //·¿Ô´µÄ×î´ó×îСֵ + Integer[] extrmeValue = houseService.findExtremeTotalPrice(city, null); + if (extrmeValue == null) { + return null; + } - try { - Value itemValue = null; - if (vals.length == 1) { - itemValue = new Value(Integer.parseInt(vals[0]), extrmeValue[1], item.getValue()); - } else if (vals.length == 2) { - if (vals[1] == null || "".equals(vals[1])) { - itemValue = new Value(Integer.parseInt(vals[0]), extrmeValue[1], item.getValue()); - } else { - itemValue = new Value(Integer.parseInt(vals[0]), Integer.parseInt(vals[1]), item.getValue()); - } - } - if(itemValue.getMin() == 0 && extrmeValue[0] < itemValue.getMax()) { - itemValue.setMin(extrmeValue[0]); - } + List items = menuService.getItems(ServerAreaData.getServerAreaByDisplay(city), MenuCategoryEnum.ershoufang, "totalPriceRange"); + for (Item item : items) { + String[] vals = item.getValue().split("_"); + if (vals == null || vals.length == 0) { + continue; + } - if (totalPrice >= itemValue.getMin() && totalPrice < itemValue.getMax()) { - inthisValue = itemValue; - inthisValue.setName(item.getName()); - } + try { + Value itemValue = null; + if (vals.length == 1) { + itemValue = new Value(Integer.parseInt(vals[0]), extrmeValue[1], item.getValue()); + } else if (vals.length == 2) { + if (vals[1] == null || "".equals(vals[1])) { + itemValue = new Value(Integer.parseInt(vals[0]), extrmeValue[1], item.getValue()); + } else { + itemValue = new Value(Integer.parseInt(vals[0]), Integer.parseInt(vals[1]), item.getValue()); + } + } + if (itemValue.getMin() == 0 && extrmeValue[0] < itemValue.getMax()) { + itemValue.setMin(extrmeValue[0]); + } - if(itemValue.getMax() < totalPrice) { - baseLessThan += (rangeMap.containsKey(item.getName()) ? rangeMap.get(item.getName()) : 0); - } + if (totalPrice >= itemValue.getMin() && totalPrice < itemValue.getMax()) { + inthisValue = itemValue; + inthisValue.setName(item.getName()); + } - if(itemValue.getMin() > totalPrice) { - baseGreaterThan += (rangeMap.containsKey(item.getName()) ? rangeMap.get(item.getName()) : 0); - } - } catch (Exception e) { - return null; - } - } + if (itemValue.getMax() < totalPrice) { + baseLessThan += (rangeMap.containsKey(item.getName()) ? rangeMap.get(item.getName()) : 0); + } - if(inthisValue != null) { - double p = ((totalPrice - inthisValue.getMin()) / (double)VALUE_SKIP) / ((inthisValue.getMax() - inthisValue.getMin()) / (double)VALUE_SKIP); - if(rangeMap.containsKey(inthisValue.getName())) { - baseLessThan += p * rangeMap.get(inthisValue.getName()); - baseGreaterThan += ((1.0 - p) * rangeMap.get(inthisValue.getName())); - } - } + if (itemValue.getMin() > totalPrice) { + baseGreaterThan += (rangeMap.containsKey(item.getName()) ? rangeMap.get(item.getName()) : 0); + } + } catch (Exception e) { + return null; + } + } - return new double[]{(int)((double)baseLessThan / (double)totalCount * 10000) / 100.0, (int)((double)baseGreaterThan / (double)totalCount * 10000) / 100.0}; - } + if (inthisValue != null) { + double p = ((totalPrice - inthisValue.getMin()) / (double) VALUE_SKIP) / ((inthisValue.getMax() - inthisValue.getMin()) / (double) VALUE_SKIP); + if (rangeMap.containsKey(inthisValue.getName())) { + baseLessThan += p * rangeMap.get(inthisValue.getName()); + baseGreaterThan += ((1.0 - p) * rangeMap.get(inthisValue.getName())); + } + } - @Authority(role = Role.USER) - public Object searchAction(final HouseSearchModel model) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if (StringUtils.isBlank(model.getResidenceId())) { - mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "Ð¡ÇøID(residenceId)²»ÄÜΪ¿Õ")); - return mav; - } - if (StringUtils.isNotBlank(model.getFloor()) && !StringUtil.isInteger(model.getFloor())) { - mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "Â¥²ã(floor)±ØÐëÊÇÊý×Ö")); - return mav; - } - if (StringUtils.isNotBlank(model.getHouseNo()) && !StringUtil.isInteger(model.getUnitNo())) { - mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "Â¥ºÅ((unitNo)±ØÐëÊÇÊý×Ö")); - return mav; - } - if (model.getSize() == null) { - mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "ÇëÊäÈë·¿ÎÝÃæ»ý(size)")); - return mav; - } - if (StringUtils.isBlank(model.getEstateType())) { - mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "ÇëÊäÈëÎïÒµÀàÐͱàÂë(estateType)")); - return mav; - } else { - String estateType = getEstateType(model.getEstateType()); - if (estateType == null) { - mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "ÇëÊäÈëÕýÈ·µÄÎïÒµÀàÐͱàÂë")); - return mav; - } - model.setEstateType(estateType); - } - if (StringUtils.isNotBlank(model.getBuildingType())) { - String buildingType = getBulidType(model.getBuildingType()); - if (buildingType == null) { - mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "ÇëÊäÈëÕýÈ·µÄ½¨ÖþÀàÐͱàÂë")); - return mav; - } else { - model.setBuildingType(buildingType); - } - } - District district = districtService.findById(model.getResidenceId(), INCLUDE_DISTRICT_FIELDS); - if (district == null) { - mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "ûÓÐÕÒµ½Ïà¹ØµÄÂ¥ÅÌ:Ð¡ÇøÒÑɾ³ý")); - return mav; - } + return new double[]{(int) ((double) baseLessThan / (double) totalCount * 10000) / 100.0, (int) ((double) baseGreaterThan / (double) totalCount * 10000) / 100.0}; + } - Date endDate = getLatestStatIndex(district.getCity()); - if (endDate == null) { - mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "ûÓÐÕÒµ½Ïà¹ØµÄÂ¥ÅÌ:²»´æÔÚÐ¡ÇøËùÔÚ³ÇÊеÄÖ¸ÊýÊý¾Ý")); - return mav; - } + @Authority(role = Role.USER) + public Object searchAction(final HouseSearchModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isBlank(model.getResidenceId())) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "Ð¡ÇøID(residenceId)²»ÄÜΪ¿Õ")); + return mav; + } + if (StringUtils.isNotBlank(model.getFloor()) && !StringUtil.isInteger(model.getFloor())) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "Â¥²ã(floor)±ØÐëÊÇÊý×Ö")); + return mav; + } + if (StringUtils.isNotBlank(model.getHouseNo()) && !StringUtil.isInteger(model.getUnitNo())) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "Â¥ºÅ((unitNo)±ØÐëÊÇÊý×Ö")); + return mav; + } + if (model.getSize() == null) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "ÇëÊäÈë·¿ÎÝÃæ»ý(size)")); + return mav; + } + if (StringUtils.isBlank(model.getEstateType())) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "ÇëÊäÈëÎïÒµÀàÐͱàÂë(estateType)")); + return mav; + } else { + String estateType = getEstateType(model.getEstateType()); + if (estateType == null) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "ÇëÊäÈëÕýÈ·µÄÎïÒµÀàÐͱàÂë")); + return mav; + } + model.setEstateType(estateType); + } + if (StringUtils.isNotBlank(model.getBuildingType())) { + String buildingType = getBulidType(model.getBuildingType()); + if (buildingType == null) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "ÇëÊäÈëÕýÈ·µÄ½¨ÖþÀàÐͱàÂë")); + return mav; + } else { + model.setBuildingType(buildingType); + } + } + District district = districtService.findById(model.getResidenceId(), INCLUDE_DISTRICT_FIELDS); + if (district == null) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "ûÓÐÕÒµ½Ïà¹ØµÄÂ¥ÅÌ:Ð¡ÇøÒÑɾ³ý")); + return mav; + } - // ×é×°Êý¾Ý - Map resMap = new LinkedHashMap(); - FacetQueryResult houseBoList = new FacetQueryResult(); - resMap.put("city", DistrictCodeUtils.getCityCode(district.getCity())); - resMap.put("region", district.getRegion()); - resMap.put("name", district.getName()); + Date endDate = getLatestStatIndex(district.getCity()); + if (endDate == null) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "ûÓÐÕÒµ½Ïà¹ØµÄÂ¥ÅÌ:²»´æÔÚÐ¡ÇøËùÔÚ³ÇÊеÄÖ¸ÊýÊý¾Ý")); + return mav; + } - // ²é·¿Ô´ - FacetQueryResult houseList = findDistrictHouses(district, null); - boolean showDetail = false; - if (model.getShowDetail() != null && model.getShowDetail().booleanValue() == true) { - showDetail = true; - } + // ×é×°Êý¾Ý + Map resMap = new LinkedHashMap(); + FacetQueryResult houseBoList = new FacetQueryResult(); + resMap.put("city", DistrictCodeUtils.getCityCode(district.getCity())); + resMap.put("region", district.getRegion()); + resMap.put("name", district.getName()); - houseBoList.addAll(fillDistrictInfoForHouse(houseList, endDate, district, showDetail, true)); - if (houseBoList.size() < 5) { - if (HouseValidator.validateEstateType(model.getEstateType())) { - district.setEstateType2(model.getEstateType()); - } - List districts = districtService.findSimilarityDistrict(district, 1000, 3);// ²éÕÒÒ»¹«ÀïÒÔÄÚÏàËÆµÄÐ¡Çø - for (District d : districts) { - d = districtService.findById(d.getId() , INCLUDE_DISTRICT_FIELDS); - if (getRemainUseYear(district) == null) { - continue; - } - district = d; - houseList = findDistrictHouses(district, null); - houseBoList.addAll(fillDistrictInfoForHouse(houseList, endDate, district, showDetail, false)); - if (houseBoList.size() > 5) { - break; - } - } - } - if (houseList.getNumberFound() > 0) { - orderHouseList(houseBoList, model); - } + // ²é·¿Ô´ + FacetQueryResult houseList = findDistrictHouses(district, null); + boolean showDetail = false; + if (model.getShowDetail() != null && model.getShowDetail().booleanValue() == true) { + showDetail = true; + } - if (houseBoList.size() > 5) { - houseBoList = new FacetQueryResult(houseBoList.subList(0, 5)); - } - if(houseBoList.isEmpty()){ - BasicModel.markNoDataRequest(); - } - resMap.put("totalCount", houseBoList.size()); - resMap.put("houses", houseBoList); - mav.setModel(resMap); - mav.setViewType("rest"); - return mav; - } + houseBoList.addAll(fillDistrictInfoForHouse(houseList, endDate, district, showDetail, true)); + if (houseBoList.size() < 5) { + if (HouseValidator.validateEstateType(model.getEstateType())) { + district.setEstateType2(model.getEstateType()); + } + List districts = districtService.findSimilarityDistrict(district, 1000, 3);// ²éÕÒÒ»¹«ÀïÒÔÄÚÏàËÆµÄÐ¡Çø + for (District d : districts) { + d = districtService.findById(d.getId(), INCLUDE_DISTRICT_FIELDS); + if (getRemainUseYear(district) == null) { + continue; + } + district = d; + houseList = findDistrictHouses(district, null); + houseBoList.addAll(fillDistrictInfoForHouse(houseList, endDate, district, showDetail, false)); + if (houseBoList.size() > 5) { + break; + } + } + } + if (houseList.getNumberFound() > 0) { + orderHouseList(houseBoList, model); + } + + if (houseBoList.size() > 5) { + houseBoList = new FacetQueryResult(houseBoList.subList(0, 5)); + } + if (houseBoList.isEmpty()) { + BasicModel.markNoDataRequest(); + } + resMap.put("totalCount", houseBoList.size()); + resMap.put("houses", houseBoList); + mav.setModel(resMap); + mav.setViewType("rest"); + return mav; + } + + @Authority(role = Role.USER) + public Object aroundAction(final HouseSearchModel model) { + List type3 = Arrays.asList("1", "2", "0"); + List type2 = Arrays.asList("1", "0"); + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isNotBlank(model.getLocationType()) && !type3.contains(model.getLocationType())) { + mav.setModel(BasicModel.buildBadRequestModel("²ÎÊý(locationType)ÓÐÎó")); + return mav; + } + if (StringUtils.isNotBlank(model.getPropertyType()) && !type3.contains(model.getPropertyType())) { + mav.setModel(BasicModel.buildBadRequestModel("²ÎÊý(propertyType)ÓÐÎó")); + return mav; + } + if (StringUtils.isNotBlank(model.getHouseType()) && !type2.contains(model.getHouseType())) { + mav.setModel(BasicModel.buildBadRequestModel("²ÎÊý(houseType)ÓÐÎó")); + return mav; + } + // »ñÈ¡µ±Ç°ÈÕÆÚ + Calendar today = Calendar.getInstance(); + + // ¸´ÖÆÒ»·Ýµ±Ç°ÈÕÆÚ£¬ÓÃÓÚ¼ÆËã°ëÄêǰµÄÈÕÆÚ + Calendar sixMonthsAgo = (Calendar) today.clone(); + + // ¼õÈ¥ 6 ¸öÔ + sixMonthsAgo.add(Calendar.MONTH, -6); + + // ¸ñʽ»¯ÈÕÆÚΪ yyyyMMdd + int todayInt = formatDate(today); + int sixMonthsAgoInt = formatDate(sixMonthsAgo); + model.setStartTime(sixMonthsAgoInt); + model.setEndTime(todayInt); + // ĬÈÏ3000MÄÚ + model.setRadius(3000); + if (StringUtils.isBlank(model.getLocation())) { + mav.setModel(BasicModel.buildBadRequestModel("location(¾­Î³¶È)²»ÄÜΪ¿Õ")); + return mav; + } + model.setLocation(model.getLocation().replace("£¬", ",")); + if (StringUtils.isBlank(model.getLocation()) || !model.getLocation().contains(",")) { + mav.setModel(BasicModel.buildBadRequestModel("location(¾­Î³¶È)²»ÄÜΪ¿Õ»ò¸ñʽ´íÎó")); + return mav; + } + String[] locationStr = model.getLocation().split(","); + String numberPattern = "-?\\d+(\\.\\d+)?"; // Æ¥ÅäÕûÊý»ò¸¡µãÊý + for (String loc : locationStr) { + if (!loc.trim().matches(numberPattern)) { + mav.setModel(BasicModel.buildBadRequestModel("location(¾­Î³¶È)¸ñʽ´íÎó")); + return mav; + } + } + Double lng = Double.valueOf(locationStr[0]); + Double lat = Double.valueOf(locationStr[1]); + +// if (model.getSize()) + if ("2".equals(model.getLocationType())) { + Map gcj02Location = GeoUtils.bd09ToGcj02(lat, lng); + lng = gcj02Location.get("lng"); + lat = gcj02Location.get("lat"); + } + if (lng < 70 || lng > 140 || lat < 0 || lat > 55) { + mav.setModel(BasicModel.buildBadRequestModel("·ÇÖйú¾­Î³¶È")); + return mav; + } + String category = "district"; + if ("1".equals(model.getPropertyType())) { + category = "office"; + } else if ("2".equals(model.getPropertyType())) { + category = "shop"; + } + + String cat = "sell"; + if ("1".equals(model.getHouseType())) { + if ("1".equals(model.getPropertyType())) { + cat = "office_rent"; + } else if ("2".equals(model.getPropertyType())) { + cat = "shop_rent"; + } else { + cat = "rent"; + } + } else { + if ("1".equals(model.getPropertyType())) { + cat = "office_sell"; + } + if ("2".equals(model.getPropertyType())) { + cat = "shop_sell"; + } + } + List houses = null; + List houseList = new ArrayList(); +// if (cat.contains("_")) { + // ÉÌÆÌ£¬Ð´×ÖÂ¥Óо­Î³¶È£¬Ö±½Ó²é + SeawaterQuery query = new SeawaterQuery(); + query.setLat(lat); + query.setLng(lng); + query.setCat(cat); + query.setRadius(model.getRadius()); + query.setStartDate(model.getStartTime()); + query.setEndDate(model.getEndTime()); + if (model.getSize() != null && model.getSize() != 0) { + query.setStartArea(model.getSize() * 0.9); + query.setEndArea(model.getSize() * 1.1); + } + query.setCityDisplay(model.getCity()); + Pager pager = new Pager(); + pager.setStartRow(0); + if (model.getPageSize() != null && model.getPageSize() > 0) { + pager.setPageSize(model.getPageSize()); + } else { + pager.setPageSize(5); + } + query.setPager(pager); + query.setTable("latest_seawater"); + houses = seawaterDao.findSeawatersByQuery(query); + if (houses != null && !houses.isEmpty()) { + for (Seawater house : houses) { + Seawater seawater = new Seawater(); + seawater.setId(house.getId()); + seawater.setCity(house.getCity()); + seawater.setDistrict(house.getRegion()); + seawater.setAddress(house.getAddress()); + seawater.setName(house.getDistrictName()); + String name = house.getName(); + if (!"ÔÝÎÞÊý¾Ý".equals(name) && StringUtils.isNotBlank(name)) { + seawater.setTitle(name); + } + if (cat.contains("office")) { + seawater.setLevel(house.getLevel()); + } + if (cat.contains("shop")) { + if (StringUtils.isNotBlank(house.getEstateType()) && !"ÆäËû".equals(house.getEstateType())) { + seawater.setShopType(house.getEstateType()); + } + if (StringUtils.isNotBlank(house.getBusinessRange())) { + seawater.setBusinessScope(house.getBusinessRange()); + } + } + seawater.setSize(house.getArea() == null || house.getArea() == 0 ? null : house.getArea()); + seawater.setUnitPrice(house.getAvgPrice() == null || house.getAvgPrice() == 0 ? null : house.getAvgPrice()); + seawater.setTotalPrice(house.getTotalPrice() == null || house.getTotalPrice() == 0 ? null : house.getTotalPrice()); + seawater.setDirection(house.getDirection()); + seawater.setFloor(house.getFloor() == null || house.getFloor() == 0 ? null : house.getFloor()); + seawater.setMaxFloor(house.getHeight() == null || house.getHeight() == 0 ? null : house.getHeight()); + seawater.setRoom(house.getRoom() == null || house.getRoom() == 0 ? null : house.getRoom()); + seawater.setHall(house.getHall() == null || house.getHall() == 0 ? null : house.getHall()); + seawater.setToilet(house.getToilet() == null || house.getToilet() == 0 ? null : house.getToilet()); + seawater.setDecoration(house.getFitment()); + if (house.getpDate() != null && house.getpDate() > 10000000) { + String numberStr = String.valueOf(house.getpDate()); + // ²ð·Ö×Ö·û´®²¢¸ñʽ»¯ + String year = numberStr.substring(0, 4); // ǰËÄλÊÇÄê·Ý + String month = numberStr.substring(4, 6); // ÖмäÁ½Î»ÊÇÔÂ·Ý + String day = numberStr.substring(6, 8); // ×îºóÁ½Î»ÊÇÈÕÆÚ + String formattedDate = year + "-" + month + "-" + day; + seawater.setPublishDate(formattedDate); + } + seawater.setDistance(house.getDistance()); + if (StringUtils.isNotBlank(house.getLocation())) { + if ("2".equals(model.getLocationType())) { + String[] split = house.getLocation().split(","); + Double lon = Double.valueOf(split[0]); + Double latt = Double.valueOf(split[1]); + Map toBd09 = GeoUtils.gcj02ToBd09(latt, lon); + seawater.setLocation(sub6(toBd09.get("lng")) + "," + sub6(toBd09.get("lat"))); + } else { + String location = house.getLocation(); + String[] split = location.split(","); + if (split.length == 2) { + String location1 = sub6(Double.valueOf(split[0])) + "," + sub6(Double.valueOf(split[1])); + seawater.setLocation(location1); + } + } + } + houseList.add(seawater); + } + } +// } else { +// if ("sell".equals(cat)) { +// List houseByLocation = houseService.findNearestHasHouseByLocation(model.getCity(), lat, lng, cat, model.getRadius(), 5); +// for (House house : houseByLocation) { +// Seawater seawater = new Seawater(); +// seawater.setId(house.getId()); +// seawater.setCity(house.getCity()); +// seawater.setDistrict(house.getRegion()); +// seawater.setAddress(house.getAddress()); +// seawater.setName(house.getDistrictName()); +// seawater.setSize(house.getArea() == null || house.getArea() == 0 ? null : house.getArea()); +// seawater.setUnitPrice(house.getAvgPrice() == null || house.getAvgPrice() == 0 ? null : house.getAvgPrice()); +// seawater.setTotalPrice(house.getTotalPrice() == null || house.getTotalPrice() == 0 ? null : house.getTotalPrice()); +// seawater.setDirection(house.getDirection()); +// seawater.setFloor(house.getFloor() == null || house.getFloor() == 0 ? null : house.getFloor()); +// seawater.setMaxFloor(house.getHeight() == null || house.getHeight() == 0 ? null : house.getHeight()); +// seawater.setRoom(house.getRoom() == null || house.getRoom() == 0 ? null : house.getRoom()); +// seawater.setHall(house.getHall() == null || house.getHall() == 0 ? null : house.getHall()); +// seawater.setToilet(house.getToilet() == null || house.getToilet() == 0 ? null : house.getToilet()); +// if (house.getAvgPrice() != null && house.getAvgPrice() != 0) { +// seawater.setUnitPrice(house.getAvgPrice()); +// } else { +// if (house.getTotalPrice() != null && house.getTotalPrice() > 0 && house.getArea() != null && house.getArea() > 0) { +// int price = (int) (house.getTotalPrice() / house.getArea()); +// seawater.setUnitPrice(price == 0 ? null : price); +// } +// } +// seawater.setDecoration(house.getFitment()); +// if (house.getPublishDate() != null) { +// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); +// seawater.setPublishDate(sdf.format(house.getPublishDate())); +// } +// houseList.add(seawater); +// } +// } else if ("rent".equals(cat)) { +// List rentHouseByLocation = rentHouseService.findNearestHasHouseByLocation(model.getCity(), lat, lng, cat, model.getRadius(), 5); +// for (RentHouse house : rentHouseByLocation) { +// Seawater seawater = new Seawater(); +// seawater.setId(house.getId()); +// seawater.setCity(house.getCity()); +// seawater.setDistrict(house.getRegion()); +// seawater.setAddress(house.getAddress()); +// seawater.setName(house.getDistrictName()); +// seawater.setSize(house.getArea() == null || house.getArea() == 0 ? null : house.getArea()); +// seawater.setUnitPrice(house.getAvgPrice() == null || house.getAvgPrice() == 0 ? null : house.getAvgPrice()); +// seawater.setTotalPrice(house.getTotalPrice() == null || house.getTotalPrice() == 0 ? null : house.getTotalPrice()); +// seawater.setDirection(house.getDirection()); +// seawater.setFloor(house.getFloor() == null || house.getFloor() == 0 ? null : house.getFloor()); +// seawater.setMaxFloor(house.getHeight() == null || house.getHeight() == 0 ? null : house.getHeight()); +// seawater.setRoom(house.getRoom() == null || house.getRoom() == 0 ? null : house.getRoom()); +// seawater.setHall(house.getHall() == null || house.getHall() == 0 ? null : house.getHall()); +// seawater.setToilet(house.getToilet() == null || house.getToilet() == 0 ? null : house.getToilet()); +// if (house.getAvgPrice() != null && house.getAvgPrice() != 0) { +// seawater.setUnitPrice(house.getAvgPrice()); +// } else { +// if (house.getTotalPrice() != null && house.getTotalPrice() > 0 && house.getArea() != null && house.getArea() > 0) { +// int price = (int) (house.getTotalPrice() / house.getArea()); +// seawater.setUnitPrice(price == 0 ? null : price); +// } +// } +// seawater.setDecoration(house.getFitment()); +// if (house.getPublishDate() != null) { +// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); +// seawater.setPublishDate(sdf.format(house.getPublishDate())); +// } +// houseList.add(seawater); +// } +// } +// } - public Object caseAction(@Valid SampleQuery sampleQuery){ + BasicModel basicModel = new BasicModel(200, "ok"); + // ×é×°Êý¾Ý + basicModel.setResult(houseList); + mav.setModel(basicModel); + mav.setViewType("rest"); + return mav; + } - RestfulModelAndView mav = new RestfulModelAndView(); - List querys = null; - try{ - querys = convertSampileQueryToBean(sampleQuery); - }catch (Exception e){ - mav.setModel(BasicModel.buildBadRequestModel(e.getMessage())); - return mav; - } - if(null == sampleQuery.getMax()){ - sampleQuery.setMax(10); - } - long start = System.currentTimeMillis(); - List collaterals = czbankSampleService.findSample2(querys, sampleQuery.getMax()); - long end = System.currentTimeMillis(); - System.out.println("ÓÃʱ:"+(end-start)); - Collateral collateral = collaterals.get(0); - List samples = collateral.getSample(); - UniversalDto dto = UniversalDto.newDto(); - if(null != collateral.getMaxPrice()){ - dto.append("maxUnitPrice", collateral.getMaxPrice()); - } - if(null != collateral.getMinPrice()){ - dto.append("minUnitPrice", collateral.getMinPrice()); - } + public Object rentAction(final HouseSearchModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (model.getSize() != null && model.getSize() < 0) { + mav.setModel(BasicModel.buildBadRequestModel("²ÎÊý(size)ÓÐÎó")); + return mav; + } + if (StringUtils.isBlank(model.getCity()) || StringUtils.isBlank(model.getDistrict()) || StringUtils.isBlank(model.getName())) { + mav.setModel(BasicModel.buildBadRequestModel("³ÇÊÐ(city),ÇøÓò(district),Ð¡ÇøÃû(name)Ϊ±ØÌî²ÎÊý")); + return mav; + } + District property = districtService.findByNameAndAlias(model.getCity(), model.getDistrict(), model.getName(), "district"); + if (null == property) { + mav.setModel(BasicModel.buildBadRequestModel("δÕÒµ½¸ÃÐ¡Çø")); + return mav; + } - dto.append("datas", samples); + // »ñÈ¡µ±Ç°ÈÕÆÚ + Calendar today = Calendar.getInstance(); + + // ¸´ÖÆÒ»·Ýµ±Ç°ÈÕÆÚ£¬ÓÃÓÚ¼ÆËã°ëÄêǰµÄÈÕÆÚ + Calendar sixMonthsAgo = (Calendar) today.clone(); + + // ¼õÈ¥ 6 ¸öÔ + sixMonthsAgo.add(Calendar.MONTH, -6); + + // ¸ñʽ»¯ÈÕÆÚΪ yyyyMMdd + int todayInt = formatDate(today); + int sixMonthsAgoInt = formatDate(sixMonthsAgo); + model.setStartTime(sixMonthsAgoInt); + model.setEndTime(todayInt); + + List houses = null; + List houseList = new ArrayList(); +// if (cat.contains("_")) { + // ÉÌÆÌ£¬Ð´×ÖÂ¥Óо­Î³¶È£¬Ö±½Ó²é + SeawaterQuery query = new SeawaterQuery(); + query.setCat("rent"); + query.setStartDate(model.getStartTime()); + query.setEndDate(model.getEndTime()); + if (model.getSize() != null && model.getSize() != 0) { + query.setStartArea(model.getSize() * 0.9); + query.setEndArea(model.getSize() * 1.1); + } + query.setCityDisplay(model.getCity()); + query.setRegion(model.getDistrict()); + query.setDistrictName(model.getName()); + query.setDistrictAlias(property.getAlias()); + Pager pager = new Pager(); + pager.setStartRow(0); + pager.setPageSize(5); + query.setPager(pager); + query.setTable("latest_seawater"); + houses = seawaterDao.findSeawatersByQuery(query); + if (houses != null && !houses.isEmpty()) { + for (Seawater house : houses) { + Seawater seawater = new Seawater(); + seawater.setId(house.getId()); + seawater.setCity(house.getCity()); + seawater.setDistrict(house.getRegion()); + seawater.setAddress(house.getAddress()); + seawater.setName(house.getDistrictName()); + String name = house.getName(); + if (!"ÔÝÎÞÊý¾Ý".equals(name) && StringUtils.isNotBlank(name)) { + seawater.setTitle(name); + } + seawater.setSize(house.getArea() == null || house.getArea() == 0 ? null : house.getArea()); + seawater.setUnitPrice(house.getAvgPrice() == null || house.getAvgPrice() == 0 ? null : house.getAvgPrice()); + seawater.setTotalPrice(house.getTotalPrice() == null || house.getTotalPrice() == 0 ? null : house.getTotalPrice()); + seawater.setDirection(house.getDirection()); + seawater.setFloor(house.getFloor() == null || house.getFloor() == 0 ? null : house.getFloor()); + seawater.setMaxFloor(house.getHeight() == null || house.getHeight() == 0 ? null : house.getHeight()); + seawater.setRoom(house.getRoom() == null || house.getRoom() == 0 ? null : house.getRoom()); + seawater.setHall(house.getHall() == null || house.getHall() == 0 ? null : house.getHall()); + seawater.setToilet(house.getToilet() == null || house.getToilet() == 0 ? null : house.getToilet()); + seawater.setDecoration(house.getFitment()); + if (house.getpDate() != null && house.getpDate() > 10000000) { + String numberStr = String.valueOf(house.getpDate()); + // ²ð·Ö×Ö·û´®²¢¸ñʽ»¯ + String year = numberStr.substring(0, 4); // ǰËÄλÊÇÄê·Ý + String month = numberStr.substring(4, 6); // ÖмäÁ½Î»ÊÇÔÂ·Ý + String day = numberStr.substring(6, 8); // ×îºóÁ½Î»ÊÇÈÕÆÚ + String formattedDate = year + "-" + month + "-" + day; + seawater.setPublishDate(formattedDate); + } + houseList.add(seawater); + } + } + BasicModel basicModel = new BasicModel(200, "ok"); + // ×é×°Êý¾Ý + basicModel.setResult(houseList); + mav.setModel(basicModel); + mav.setViewType("rest"); + return mav; + } + + public Object resourcesAction(final HouseSearchModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (model.getSize() != null && model.getSize() < 0) { + mav.setModel(BasicModel.buildBadRequestModel("²ÎÊý(size)ÓÐÎó")); + return mav; + } + if (StringUtils.isBlank(model.getCity()) || StringUtils.isBlank(model.getDistrict()) || StringUtils.isBlank(model.getName())) { + mav.setModel(BasicModel.buildBadRequestModel("³ÇÊÐ(city),ÇøÓò(district),Ð¡ÇøÃû(name)Ϊ±ØÌî²ÎÊý")); + return mav; + } + District property = districtService.findByNameAndAlias(model.getCity(), model.getDistrict(), model.getName(), "district"); + if (null == property) { + mav.setModel(BasicModel.buildBadRequestModel("δÕÒµ½¸ÃÐ¡Çø")); + return mav; + } + // ûÓÐÊäÈëʱ¼ä·¶Î§£¬ÔòÊÇĬÈÏÁù¸öÔ嵀 + if (model.getStartTime() == null && model.getEndTime() == null) { + // »ñÈ¡µ±Ç°ÈÕÆÚ + Calendar today = Calendar.getInstance(); + + // ¸´ÖÆÒ»·Ýµ±Ç°ÈÕÆÚ£¬ÓÃÓÚ¼ÆËã°ëÄêǰµÄÈÕÆÚ + Calendar sixMonthsAgo = (Calendar) today.clone(); + + // ¼õÈ¥ 6 ¸öÔ + sixMonthsAgo.add(Calendar.MONTH, -6); + + // ¸ñʽ»¯ÈÕÆÚΪ yyyyMMdd + int todayInt = formatDate(today); + int sixMonthsAgoInt = formatDate(sixMonthsAgo); + model.setStartTime(sixMonthsAgoInt); + model.setEndTime(todayInt); + } + + List houses = null; + List houseList = new ArrayList(); + SeawaterQuery query = new SeawaterQuery(); + List catList = Arrays.asList("rent", "sell", "office_rent", "office_sell", "shop_sell", "shop_rent"); + if (!catList.contains(model.getCat())) { + model.setCat("rent"); + } + query.setCat(model.getCat()); + query.setStartDate(model.getStartTime()); + query.setEndDate(model.getEndTime()); + if (model.getSize() != null && model.getSize() != 0) { + query.setStartArea(model.getSize() * 0.9); + query.setEndArea(model.getSize() * 1.1); + } + query.setCityDisplay(model.getCity()); + query.setRegion(model.getDistrict()); + query.setDistrictName(model.getName()); + query.setDistrictAlias(property.getAlias()); + Pager pager = new Pager(); + // ûÓвéѯÊýÁ¿£¬Ä¬ÈϲéǰÎå¸ö + if (model.getPageIndex() == null) { + pager.setStartRow(0); + } else { + pager.setStartRow(model.getPageIndex()); + } + pager.setPageSize(model.getPageSize()); + query.setPager(pager); + query.setTable("latest_seawater"); + if (StringUtils.isNotBlank(model.getSortField())) { + query.setSortField(model.getSortField()); + } else { + query.setSortField("p_date"); + } + if ("asc".equals(model.getSortBy())) { + query.setOrder(true); + } else { + query.setOrder(false); + } + houses = seawaterDao.findSeawatersByQuery(query); + if (houses != null && !houses.isEmpty()) { + for (Seawater house : houses) { + Seawater seawater = new Seawater(); + seawater.setId(house.getId()); + seawater.setCity(house.getCity()); + seawater.setDistrict(house.getRegion()); + seawater.setAddress(house.getAddress()); + seawater.setName(house.getDistrictName()); + String name = house.getName(); + if (!"ÔÝÎÞÊý¾Ý".equals(name) && StringUtils.isNotBlank(name)) { + seawater.setTitle(name); + } + seawater.setSize(house.getArea() == null || house.getArea() == 0 ? null : house.getArea()); + seawater.setUnitPrice(house.getAvgPrice() == null || house.getAvgPrice() == 0 ? null : house.getAvgPrice()); + seawater.setTotalPrice(house.getTotalPrice() == null || house.getTotalPrice() == 0 ? null : house.getTotalPrice()); + seawater.setDirection(house.getDirection()); + seawater.setFloor(house.getFloor() == null || house.getFloor() == 0 ? null : house.getFloor()); + seawater.setMaxFloor(house.getHeight() == null || house.getHeight() == 0 ? null : house.getHeight()); + seawater.setRoom(house.getRoom() == null || house.getRoom() == 0 ? null : house.getRoom()); + seawater.setHall(house.getHall() == null || house.getHall() == 0 ? null : house.getHall()); + seawater.setToilet(house.getToilet() == null || house.getToilet() == 0 ? null : house.getToilet()); + seawater.setDecoration(house.getFitment()); + seawater.setFloorInfo(house.getFloorInfo()); + seawater.setRoot(house.getRoot()); + if (house.getpDate() != null && house.getpDate() > 10000000) { + String numberStr = String.valueOf(house.getpDate()); + // ²ð·Ö×Ö·û´®²¢¸ñʽ»¯ + String year = numberStr.substring(0, 4); // ǰËÄλÊÇÄê·Ý + String month = numberStr.substring(4, 6); // ÖмäÁ½Î»ÊÇÔÂ·Ý + String day = numberStr.substring(6, 8); // ×îºóÁ½Î»ÊÇÈÕÆÚ + String formattedDate = year + "-" + month + "-" + day; + seawater.setPublishDate(formattedDate); + } + houseList.add(seawater); + } + } + BasicPageModel pageModel = new BasicPageModel(200, "ok"); + pager.setPageSize(-1); + pager.setStartRow(-1); + query.setPager(pager); + long count = seawaterDao.findSeawatersCountByQuery(query); + pageModel.setTotal((int) count); + // ×é×°Êý¾Ý + pageModel.setResult(houseList); + mav.setModel(pageModel); + mav.setViewType("rest"); + return mav; + } + + Double sub6(Double a) { + BigDecimal bd = new BigDecimal(a); + BigDecimal bigDecimal = bd.setScale(6, BigDecimal.ROUND_DOWN); + return bigDecimal.doubleValue(); + } + + // ¸ñʽ»¯ÈÕÆÚΪ yyyyMMdd + private static int formatDate(Calendar calendar) { + int year = calendar.get(Calendar.YEAR); + int month = calendar.get(Calendar.MONTH) + 1; // Ô·ÝÊÇ´Ó 0 ¿ªÊ¼µÄ + int day = calendar.get(Calendar.DAY_OF_MONTH); + + // ·µ»Ø¸ñʽ»¯ºóµÄÕûÊý + return year * 10000 + month * 100 + day; + } + + + public Object caseAction(@Valid SampleQuery sampleQuery) { + + RestfulModelAndView mav = new RestfulModelAndView(); + List querys = null; + try { + querys = convertSampileQueryToBean(sampleQuery); + } catch (Exception e) { + mav.setModel(BasicModel.buildBadRequestModel(e.getMessage())); + return mav; + } + if (null == sampleQuery.getMax()) { + sampleQuery.setMax(10); + } + long start = System.currentTimeMillis(); + List collaterals = czbankSampleService.findSample2(querys, sampleQuery.getMax()); + long end = System.currentTimeMillis(); + System.out.println("ÓÃʱ:" + (end - start)); + Collateral collateral = collaterals.get(0); + List samples = collateral.getSample(); + UniversalDto dto = UniversalDto.newDto(); + if (null != collateral.getMaxPrice()) { + dto.append("maxUnitPrice", collateral.getMaxPrice()); + } + if (null != collateral.getMinPrice()) { + dto.append("minUnitPrice", collateral.getMinPrice()); + } + + dto.append("datas", samples); // if(samples!= null && samples.size()>=2){ // Sample minSample = samples.get(samples.size()-2); // Sample maxSample = samples.get(samples.size()-1); @@ -930,160 +1424,158 @@ public class HouseController { // dto.append("datas", samples); // } - mav.setModel(BasicModel.buildOKModel().setResult(dto)); - return mav; - } + mav.setModel(BasicModel.buildOKModel().setResult(dto)); + return mav; + } + private List fillDistrictInfoForHouse(FacetQueryResult houseList, Date endDate, + District district, boolean showDetail, boolean matchModel) { + FacetQueryResult list = new FacetQueryResult(); + String estateType; + if (district.getEstateType2() != null && ESTATE_TYPE_CODE.containsKey(district.getEstateType2())) { + estateType = ESTATE_TYPE_CODE.get(district.getEstateType2()); + } else { + estateType = "4"; + } + String buildingStructure = district.getBuildStructure(); + DistrictFacilitys districtFacilitys = districtFacilitysService.findDistrictFacilitys(new DistrictKey(district.getCity(), + district.getRegion(), district.getName())); + int schoolAmount; + if (districtFacilitys != null && districtFacilitys.getSchool() != null) { + schoolAmount = districtFacilitys.getSchool().size(); + if (schoolAmount > 20) { + schoolAmount = 20; + } + } else { + schoolAmount = 0; + } + int busStationAmount; + if (districtFacilitys != null && districtFacilitys.getBus() != null) { + busStationAmount = districtFacilitys.getBus().size(); + } else { + busStationAmount = 0; + } + int communityPrice = districtStatService.findLatestDistrictAvgPrice(district.getCity(), district.getRegion(), + district.getBlock(), district.getName()); + int metroStationAmount = 0; + if (district.getLng2() != null && district.getLat2() != null) { + List metroList = metroService + .findNearbyMetro(district.getCity(), district.getLng2(), district.getLat2(), 1000); + if (metroList != null) { + metroStationAmount = metroList.size(); + } + } + String buildDate = null, remainUseYear = null; + if (district.getBuildDate() != null || district.getFinishBuildingDate() != null || district.getLiveDate() != null || district.getOpenDate() != null) { + Integer minYear = getBuildYear(district.getFinishBuildingDate(), district.getLiveDate(), district.getBuildDate(), district.getOpenDate()); + if (minYear != null && minYear > 0) { + buildDate = minYear + "Äê"; + if (getHouseUseYear(minYear, district.getPropertyLife()) != null) { + remainUseYear = getHouseUseYear(minYear, district.getPropertyLife()) + "Äê";// Ê£ÓàʹÓÃÄêÏÞ + } + } + } - private List fillDistrictInfoForHouse(FacetQueryResult houseList, Date endDate, - District district, boolean showDetail, boolean matchModel) { - FacetQueryResult list = new FacetQueryResult(); - String estateType; - if (district.getEstateType2() != null && ESTATE_TYPE_CODE.containsKey(district.getEstateType2())) { - estateType = ESTATE_TYPE_CODE.get(district.getEstateType2()); - } else { - estateType = "4"; - } - String buildingStructure = district.getBuildStructure(); - DistrictFacilitys districtFacilitys = districtFacilitysService.findDistrictFacilitys(new DistrictKey(district.getCity(), - district.getRegion(), district.getName())); - int schoolAmount; - if (districtFacilitys != null && districtFacilitys.getSchool() != null) { - schoolAmount = districtFacilitys.getSchool().size(); - if (schoolAmount > 20) { - schoolAmount = 20; - } - } else { - schoolAmount = 0; - } - int busStationAmount; - if (districtFacilitys != null && districtFacilitys.getBus() != null) { - busStationAmount = districtFacilitys.getBus().size(); - } else { - busStationAmount = 0; - } + for (com.fangjia.service.bo.HouseBo bo : houseList) { + House house = bo.getHouse(); + HousePojo b = new HousePojo(); + b.setName(district.getName()); + b.setRegion(district.getRegion()); + b.setCity(DistrictCodeUtils.getCityCode(district.getCity())); + b.setListingPrice(house.getTotalPrice()); + b.setSize(house.getArea()); + b.setAddress(bo.getAddress() == null ? district.getAddress() : bo.getAddress()); + b.setMaxFloor(house.getHeight()); + b.setFloor(house.getFloor()); + b.setRoomAmount(house.getRoom()); + b.setHallAmount(house.getHall()); + b.setToiletAmount(house.getToilet()); + b.setPublishDate(house.getPublishDate()); + b.setEstateType(estateType); + b.setBuildingStructure(buildingStructure); + b.setBuildDate(buildDate); + b.setRemainUseYear(remainUseYear); + b.setManagementFee(district.getEstateCharge()); + b.setGreeningRatio(district.getVirescencePercent()); + b.setFloorAreaRatio(district.getCubagePercent()); + b.setMatchModel(matchModel); + if (showDetail) { + b.setUrl(house.getUrl()); + b.setUuid(house.getId()); + } + if (StringUtils.isNotBlank(district.getHouseProperty())) { + b.setHouseProperty(district.getHouseProperty()); + } + if (schoolAmount != 0) { + b.setSchoolAmount(schoolAmount); + } + if (busStationAmount != 0) { + b.setBusStationAmount(busStationAmount); + } + if (communityPrice != 0) { + b.setCommunityPrice(communityPrice); + } + if (metroStationAmount != 0) { + b.setMetroStationAmount(metroStationAmount); + } - int communityPrice = districtStatService.findLatestDistrictAvgPrice(district.getCity(), district.getRegion(), - district.getBlock(), district.getName()); - int metroStationAmount = 0; - if (district.getLng2() != null && district.getLat2() != null) { - List metroList = metroService - .findNearbyMetro(district.getCity(), district.getLng2(), district.getLat2(), 1000); - if (metroList != null) { - metroStationAmount = metroList.size(); - } - } - String buildDate = null, remainUseYear = null; - if (district.getBuildDate() != null || district.getFinishBuildingDate() != null || district.getLiveDate() != null || district.getOpenDate() != null) { - Integer minYear = getBuildYear(district.getFinishBuildingDate(), district.getLiveDate(), district.getBuildDate(),district.getOpenDate()); - if (minYear != null && minYear > 0) { - buildDate = minYear + "Äê"; - if (getHouseUseYear(minYear, district.getPropertyLife()) != null) { - remainUseYear = getHouseUseYear(minYear, district.getPropertyLife()) + "Äê";// Ê£ÓàʹÓÃÄêÏÞ - } - } - } + String fitment = HouseValidator.fetchFitmentInfo(house.getFitment()); + if (fitment == null) { + b.setDecorationCost("4"); + } else { + b.setDecorationCost(FITMENT_CODE.get(fitment)); + if (b.getDecorationCost() == null) { + b.setDecorationCost("4"); + } + } + String direction = HouseValidator.fetchDirectionInfo(house.getDirection()); + if (direction == null) { + b.setDirection("6"); + } else { + if (DIRECTION_CODE.containsKey(direction)) { + b.setDirection(DIRECTION_CODE.get(direction)); + } else { + b.setDirection("6"); + } + } - for (com.fangjia.service.bo.HouseBo bo : houseList) { - House house = bo.getHouse(); - HousePojo b = new HousePojo(); - b.setName(district.getName()); - b.setRegion(district.getRegion()); - b.setCity(DistrictCodeUtils.getCityCode(district.getCity())); - b.setListingPrice(house.getTotalPrice()); - b.setSize(house.getArea()); - b.setAddress(bo.getAddress() == null ? district.getAddress() : bo.getAddress()); - b.setMaxFloor(house.getHeight()); - b.setFloor(house.getFloor()); - b.setRoomAmount(house.getRoom()); - b.setHallAmount(house.getHall()); - b.setToiletAmount(house.getToilet()); - b.setPublishDate(house.getPublishDate()); - b.setEstateType(estateType); - b.setBuildingStructure(buildingStructure); - b.setBuildDate(buildDate); - b.setRemainUseYear(remainUseYear); - b.setManagementFee(district.getEstateCharge()); - b.setGreeningRatio(district.getVirescencePercent()); - b.setFloorAreaRatio(district.getCubagePercent()); - b.setMatchModel(matchModel); - if (showDetail) { - b.setUrl(house.getUrl()); - b.setUuid(house.getId()); - } - if (StringUtils.isNotBlank(district.getHouseProperty())) { - b.setHouseProperty(district.getHouseProperty()); - } - if (schoolAmount != 0) { - b.setSchoolAmount(schoolAmount); - } - if (busStationAmount != 0) { - b.setBusStationAmount(busStationAmount); - } - if (communityPrice != 0) { - b.setCommunityPrice(communityPrice); - } - if (metroStationAmount != 0) { - b.setMetroStationAmount(metroStationAmount); - } - - String fitment = HouseValidator.fetchFitmentInfo(house.getFitment()); - if (fitment == null) { - b.setDecorationCost("4"); - } else { - b.setDecorationCost(FITMENT_CODE.get(fitment)); - if (b.getDecorationCost() == null) { - b.setDecorationCost("4"); - } - } - String direction = HouseValidator.fetchDirectionInfo(house.getDirection()); - if (direction == null) { - b.setDirection("6"); - } else { - if (DIRECTION_CODE.containsKey(direction)) { - b.setDirection(DIRECTION_CODE.get(direction)); - } else { - b.setDirection("6"); - } - } - - b.setPublishDate(generatorDate(endDate, house.getPublishDate()));// ·¢²¼Ê±¼ä - b.setSource(getDomainName(house.getUrl())); - b.setBlock(house.getBlock()); + b.setPublishDate(generatorDate(endDate, house.getPublishDate()));// ·¢²¼Ê±¼ä + b.setSource(getDomainName(house.getUrl())); + b.setBlock(house.getBlock()); // b.setBlock(DateUtil.formatByPattern(house.getPublishDate(), "yyyy-MM-dd")); - if (StringUtils.isBlank(house.getBuildType())) { - if (BULIDS_TYPE_CODE.containsKey(district.getBuildType())) { - b.setBuildingType(BULIDS_TYPE_CODE.get(district.getBuildType())); - } else { - b.setBuildingType("00"); - } - } else { - if (BULIDS_TYPE_CODE.containsKey(house.getBuildType())) { - b.setBuildingType(BULIDS_TYPE_CODE.get(house.getBuildType())); - } else { - b.setBuildingType("00"); - } - } - String houseType = getHouseType(bo.getHouse()); - if (StringUtils.isNotBlank(houseType)) { - b.setUnitType(houseType); - } - if (b.getSize() != null && b.getListingPrice() != null && b.getSize() != 0) { - b.setAveragePrice((int) (b.getListingPrice() / b.getSize())); - if (b.getAveragePrice() > 300000 || b.getAveragePrice() < 1000) { - continue; - } - } - if (HouseValidator.validateArea(b.getSize()) && !checkExists(list, b)) { - list.add(b); - } - } - return list; - } + if (StringUtils.isBlank(house.getBuildType())) { + if (BULIDS_TYPE_CODE.containsKey(district.getBuildType())) { + b.setBuildingType(BULIDS_TYPE_CODE.get(district.getBuildType())); + } else { + b.setBuildingType("00"); + } + } else { + if (BULIDS_TYPE_CODE.containsKey(house.getBuildType())) { + b.setBuildingType(BULIDS_TYPE_CODE.get(house.getBuildType())); + } else { + b.setBuildingType("00"); + } + } + String houseType = getHouseType(bo.getHouse()); + if (StringUtils.isNotBlank(houseType)) { + b.setUnitType(houseType); + } + if (b.getSize() != null && b.getListingPrice() != null && b.getSize() != 0) { + b.setAveragePrice((int) (b.getListingPrice() / b.getSize())); + if (b.getAveragePrice() > 300000 || b.getAveragePrice() < 1000) { + continue; + } + } + if (HouseValidator.validateArea(b.getSize()) && !checkExists(list, b)) { + list.add(b); + } + } + return list; + } - private Date generatorDate(Date endDate, Date publishDate) { + private Date generatorDate(Date endDate, Date publishDate) { // List months = DateUtil.getMonthList(new Date(), 6); // Date endMonthStartDate = DateUtil.getFirstDayOfMonth(months.get(0)); // long day1 = (endDate.getTime() - endMonthStartDate.getTime()) / (long)(24 * 3600 * 1000); @@ -1092,613 +1584,620 @@ public class HouseController { // long t1 = (long)(day1 * t2 / day2 * 0.5); // return DateUtil.getBeforeDay(endDate, (int)t1); - List months = DateUtil.getMonthList(new Date(), 6); - Date endMonthStartDate = DateUtil.getFirstDayOfMonth(months.get(0)); - long diffDay = (publishDate.getTime() - endMonthStartDate.getTime()) / (long)(24 * 3600 * 1000); - int df = (int) ((173 - diffDay) * 0.5); - if(df <= 0) { - df = 1; - } + List months = DateUtil.getMonthList(new Date(), 6); + Date endMonthStartDate = DateUtil.getFirstDayOfMonth(months.get(0)); + long diffDay = (publishDate.getTime() - endMonthStartDate.getTime()) / (long) (24 * 3600 * 1000); + int df = (int) ((173 - diffDay) * 0.5); + if (df <= 0) { + df = 1; + } - Date ret = DateUtil.getBeforeDay(endDate, (int)df); - return ret; - } + Date ret = DateUtil.getBeforeDay(endDate, (int) df); + return ret; + } - public void setSeawaterService(SeawaterService seawaterService) { - this.seawaterService = seawaterService; - } + public void setSeawaterService(SeawaterService seawaterService) { + this.seawaterService = seawaterService; + } - public void setSeawaterDao(SeawaterDao seawaterDao) { - this.seawaterDao = seawaterDao; - } + public void setSeawaterDao(SeawaterDao seawaterDao) { + this.seawaterDao = seawaterDao; + } - private boolean checkExists(FacetQueryResult houseBoList, HousePojo house) { - for (HousePojo bo : houseBoList) { - boolean sameName = bo.getName().equals(house.getName()); - boolean sameAddress = bo.getAddress() != null ? bo.getAddress().equals(house.getAddress()) - : house.getAddress() == null; - boolean sameTotalPrice = bo.getListingPrice() != null ? bo.getListingPrice().equals(house.getListingPrice()) : house - .getListingPrice() == null; - boolean samePublishDate = bo.getPublishDate() != null ? bo.getPublishDate().equals(house.getPublishDate()) : house - .getPublishDate() == null; - boolean sameArea = bo.getSize() != null ? bo.getSize().equals(house.getSize()) : house.getSize() == null; - boolean sameFloor = bo.getFloor() != null ? bo.getFloor().equals(house.getFloor()) : house.getFloor() == null; - if (sameName && sameAddress && sameFloor && sameTotalPrice && samePublishDate && sameArea) { - return true; - } - } - return false; - } + private boolean checkExists(FacetQueryResult houseBoList, HousePojo house) { + for (HousePojo bo : houseBoList) { + boolean sameName = bo.getName().equals(house.getName()); + boolean sameAddress = bo.getAddress() != null ? bo.getAddress().equals(house.getAddress()) + : house.getAddress() == null; + boolean sameTotalPrice = bo.getListingPrice() != null ? bo.getListingPrice().equals(house.getListingPrice()) : house + .getListingPrice() == null; + boolean samePublishDate = bo.getPublishDate() != null ? bo.getPublishDate().equals(house.getPublishDate()) : house + .getPublishDate() == null; + boolean sameArea = bo.getSize() != null ? bo.getSize().equals(house.getSize()) : house.getSize() == null; + boolean sameFloor = bo.getFloor() != null ? bo.getFloor().equals(house.getFloor()) : house.getFloor() == null; + if (sameName && sameAddress && sameFloor && sameTotalPrice && samePublishDate && sameArea) { + return true; + } + } + return false; + } - /** - * ²éÕÒÐ¡Çø·¿Ô´ - * - * @param district - * @return - */ - private FacetQueryResult findDistrictHouses(District district, Date endDate) { - FacetQueryResult houseList = new FacetQueryResult(); - if (district == null) { - return houseList; - } - if (getRemainUseYear(district) == null) { - return houseList; - } - houseList = houseService.findHouses(district, endDate, 0, 50, INCLUDE_HOUSE_FIELDS); - if (!houseList.isEmpty()) { - return houseList; - } - return houseList; - } + /** + * ²éÕÒÐ¡Çø·¿Ô´ + * + * @param district + * @return + */ + private FacetQueryResult findDistrictHouses(District district, Date endDate) { + FacetQueryResult houseList = new FacetQueryResult(); + if (district == null) { + return houseList; + } + if (getRemainUseYear(district) == null) { + return houseList; + } + houseList = houseService.findHouses(district, endDate, 0, 50, INCLUDE_HOUSE_FIELDS); + if (!houseList.isEmpty()) { + return houseList; + } + return houseList; + } - public Date getLatestStatIndex(String city) { - String now = DateUtil.formatByPattern(new Date(), "yyyyMMdd"); - if (CACHE_REFRESH_FLAG == null || !CACHE_REFRESH_FLAG.equals(now)) { - CACHE_REFRESH_FLAG = now; - STATS_INDEX_LATEST_DATE_CACHE.clear(); - } - if (STATS_INDEX_LATEST_DATE_CACHE.containsKey(city)) { - return STATS_INDEX_LATEST_DATE_CACHE.get(city); - } + public Date getLatestStatIndex(String city) { + String now = DateUtil.formatByPattern(new Date(), "yyyyMMdd"); + if (CACHE_REFRESH_FLAG == null || !CACHE_REFRESH_FLAG.equals(now)) { + CACHE_REFRESH_FLAG = now; + STATS_INDEX_LATEST_DATE_CACHE.clear(); + } + if (STATS_INDEX_LATEST_DATE_CACHE.containsKey(city)) { + return STATS_INDEX_LATEST_DATE_CACHE.get(city); + } - StatsIndex statsIndex = statsIndexService.findLatestStstsIndex(city, null, "district"); - STATS_INDEX_LATEST_DATE_CACHE.put(city, null); - if (statsIndex == null) { - return null; - } - if (statsIndex.getBelowFixedbase() == null || statsIndex.getBelowFixedbase() == null - || statsIndex.getBelowFixedbase() == null) { - return null; - } - Date endDate = DateUtil.parseDate(statsIndex.getYearmonth(), "yyyyMM"); - Calendar c = Calendar.getInstance(); - c.setTime(endDate); - c.add(Calendar.MONTH, -1); - STATS_INDEX_LATEST_DATE_CACHE.put(city, c.getTime()); - return c.getTime(); - } + StatsIndex statsIndex = statsIndexService.findLatestStstsIndex(city, null, "district"); + STATS_INDEX_LATEST_DATE_CACHE.put(city, null); + if (statsIndex == null) { + return null; + } + if (statsIndex.getBelowFixedbase() == null || statsIndex.getBelowFixedbase() == null + || statsIndex.getBelowFixedbase() == null) { + return null; + } + Date endDate = DateUtil.parseDate(statsIndex.getYearmonth().toString(), "yyyyMM"); + Calendar c = Calendar.getInstance(); + c.setTime(endDate); + c.add(Calendar.MONTH, -1); + STATS_INDEX_LATEST_DATE_CACHE.put(city, c.getTime()); + return c.getTime(); + } - private void orderHouseList(FacetQueryResult houseBoList, final HouseSearchModel model) { - Integer floor = null; - final Double area = model.getSize(); - try { - floor = Integer.valueOf(model.getFloor()); - } catch (Exception e) { + private void orderHouseList(FacetQueryResult houseBoList, final HouseSearchModel model) { + Integer floor = null; + final Double area = model.getSize(); + try { + floor = Integer.valueOf(model.getFloor()); + } catch (Exception e) { - } + } - final Integer fFloor = floor; + final Integer fFloor = floor; - Collections.sort(houseBoList, new Comparator() { - @Override - public int compare(HousePojo o1, HousePojo o2) { - Double score1 = computeScore(o1); - Double score2 = computeScore(o2); - return score2.compareTo(score1); - } + Collections.sort(houseBoList, new Comparator() { + @Override + public int compare(HousePojo o1, HousePojo o2) { + Double score1 = computeScore(o1); + Double score2 = computeScore(o2); + return score2.compareTo(score1); + } - private double computeScore(HousePojo bo) { - double score = 0; - if (bo.getFloor() != null && fFloor != null) { - score += computeAreaScore(bo.getFloor(), fFloor) * 0.02; - } - if (bo.getSize() != null && area != null) { - score += computeAreaScore(bo.getSize(), area) * 0.98; - } - if ("ÆÕͨסլ".equals(model.getEstateType()) && !isVilla(bo.getName(), bo.getMaxFloor(), bo.getFloor(), bo.getSize())) { - score += 1; - } else if ("±ðÊû".equals(model.getEstateType()) - && isVilla(bo.getName(), bo.getMaxFloor(), bo.getFloor(), bo.getSize())) { - score += 1; - } + private double computeScore(HousePojo bo) { + double score = 0; + if (bo.getFloor() != null && fFloor != null) { + score += computeAreaScore(bo.getFloor(), fFloor) * 0.02; + } + if (bo.getSize() != null && area != null) { + score += computeAreaScore(bo.getSize(), area) * 0.98; + } + if ("ÆÕͨסլ".equals(model.getEstateType()) && !isVilla(bo.getName(), bo.getMaxFloor(), bo.getFloor(), bo.getSize())) { + score += 1; + } else if ("±ðÊû".equals(model.getEstateType()) + && isVilla(bo.getName(), bo.getMaxFloor(), bo.getFloor(), bo.getSize())) { + score += 1; + } - return score; - } + return score; + } - private double computeAreaScore(double a1, double a2) { - return 2 / (1 + Math.exp(Math.abs(1 - a1 / a2))); - } + private double computeAreaScore(double a1, double a2) { + return 2 / (1 + Math.exp(Math.abs(1 - a1 / a2))); + } - private boolean isVilla(String name, Integer maxFloor, Integer floor, Double size) { + private boolean isVilla(String name, Integer maxFloor, Integer floor, Double size) { - if (name != null && name.indexOf("±ðÊû") > -1) { - return true; - } + if (name != null && name.indexOf("±ðÊû") > -1) { + return true; + } - if (name != null && name.indexOf("±ðÊû") > -1 && size != null && size > 180) { - return true; - } + if (name != null && name.indexOf("±ðÊû") > -1 && size != null && size > 180) { + return true; + } - boolean flag = false; - if (maxFloor != null && maxFloor <= 4) { - if (size != null && size <= 100) { - if (size != null && size <= 50) { - flag = false; - } else { - if (maxFloor != null && maxFloor <= 0) { - if (floor != null && floor <= 0) { - if (size != null && size <= 93) { - if (size != null && size <= 88) { - flag = false; - } else { - flag = true; - } - } else { - flag = false; - } - } else { - flag = false; - } - } else { - if (floor != null && floor <= 2) { - if (size != null && size <= 98) { - flag = false; - } else { - flag = true; - } - } else { - if (maxFloor != null && maxFloor <= 3) { - flag = true; - } else { - if (floor != null && floor <= 3) { - flag = false; - } else { - flag = true; - } - } - } - } - } - } else { - flag = true; - } - } else { - if (size != null && size <= 178) { - if (size != null && size <= 143) { - flag = false; - } else { - if (maxFloor != null && maxFloor <= 8) { - if (floor != null && floor <= 2) { - flag = false; - } else { - if (maxFloor != null && maxFloor <= 5) { - if (size != null && size <= 146) { - flag = false; - } else { - if (size != null && size <= 160) { - if (size != null && size <= 158) { - if (size != null && size <= 148) { - flag = true; - } else { - flag = false; - } - } else { - flag = true; - } - } else { - flag = false; - } - } - } else { - flag = false; - } - } - } else { - flag = false; - } - } - } else { - if (size != null && size <= 300) { - if (maxFloor != null && maxFloor <= 14) { - if (size != null && size <= 200) { - if (floor != null && floor <= 4) { - if (floor != null && floor <= 3) { - if (floor != null && floor <= 2) { - flag = false; - } else { - if (maxFloor != null && maxFloor <= 5) { - flag = true; - } else { - flag = false; - } - } - } else { - flag = false; - } - } else { - if (maxFloor != null && maxFloor <= 5) { - if (size != null && size <= 192) { - flag = false; - } else { - flag = true; - } - } else { - if (maxFloor != null && maxFloor <= 8) { - if (floor != null && floor <= 6) { - flag = false; - } else { - flag = true; - } - } else { - flag = false; - } - } - } - } else { - if (maxFloor != null && maxFloor <= 5) { - if (floor != null && floor <= 4) { - if (floor != null && floor <= 3) { - if (floor != null && floor <= 1) { - flag = false; - } else { - flag = true; - } - } else { - flag = false; - } - } else { - flag = true; - } - } else { - if (maxFloor != null && maxFloor <= 10) { - if (maxFloor != null && maxFloor <= 6) { - if (size != null && size <= 223) { - if (floor != null && floor <= 1) { - flag = false; - } else { - if (size != null && size <= 206) { - flag = false; - } else { - if (size != null && size <= 215) { - flag = true; - } else { - flag = false; - } - } - } - } else { - if (floor != null && floor <= 5) { - if (floor != null && floor <= 3) { - if (floor != null && floor <= 1) { - flag = false; - } else { - flag = true; - } - } else { - flag = false; - } - } else { - flag = true; - } - } - } else { - if (size != null && size <= 267) { - if (size != null && size <= 219) { - if (size != null && size <= 208) { - flag = false; - } else { - if (size != null && size <= 214) { - flag = true; - } else { - flag = false; - } - } - } else { - flag = false; - } - } else { - if (floor != null && floor <= 4) { - flag = false; - } else { - if (size != null && size <= 286) { - flag = true; - } else { - flag = false; - } - } - } - } - } else { - if (size != null && size <= 252) { - if (size != null && size <= 249) { - if (size != null && size <= 204) { - flag = true; - } else { - if (floor != null && floor <= 2) { - flag = false; - } else { - if (maxFloor != null && maxFloor <= 11) { - flag = false; - } else { - if (size != null && size <= 228) { - flag = true; - } else { - flag = false; - } - } - } - } - } else { - flag = true; - } - } else { - flag = false; - } - } - } - } - } else { - flag = false; - } - } else { - if (size != null && size <= 340) { - if (maxFloor != null && maxFloor <= 5) { - flag = true; - } else { - if (size != null && size <= 323) { - flag = true; - } else { - flag = false; - } - } - } else { - flag = true; - } - } - } - } - return flag; - } + boolean flag = false; + if (maxFloor != null && maxFloor <= 4) { + if (size != null && size <= 100) { + if (size != null && size <= 50) { + flag = false; + } else { + if (maxFloor != null && maxFloor <= 0) { + if (floor != null && floor <= 0) { + if (size != null && size <= 93) { + if (size != null && size <= 88) { + flag = false; + } else { + flag = true; + } + } else { + flag = false; + } + } else { + flag = false; + } + } else { + if (floor != null && floor <= 2) { + if (size != null && size <= 98) { + flag = false; + } else { + flag = true; + } + } else { + if (maxFloor != null && maxFloor <= 3) { + flag = true; + } else { + if (floor != null && floor <= 3) { + flag = false; + } else { + flag = true; + } + } + } + } + } + } else { + flag = true; + } + } else { + if (size != null && size <= 178) { + if (size != null && size <= 143) { + flag = false; + } else { + if (maxFloor != null && maxFloor <= 8) { + if (floor != null && floor <= 2) { + flag = false; + } else { + if (maxFloor != null && maxFloor <= 5) { + if (size != null && size <= 146) { + flag = false; + } else { + if (size != null && size <= 160) { + if (size != null && size <= 158) { + if (size != null && size <= 148) { + flag = true; + } else { + flag = false; + } + } else { + flag = true; + } + } else { + flag = false; + } + } + } else { + flag = false; + } + } + } else { + flag = false; + } + } + } else { + if (size != null && size <= 300) { + if (maxFloor != null && maxFloor <= 14) { + if (size != null && size <= 200) { + if (floor != null && floor <= 4) { + if (floor != null && floor <= 3) { + if (floor != null && floor <= 2) { + flag = false; + } else { + if (maxFloor != null && maxFloor <= 5) { + flag = true; + } else { + flag = false; + } + } + } else { + flag = false; + } + } else { + if (maxFloor != null && maxFloor <= 5) { + if (size != null && size <= 192) { + flag = false; + } else { + flag = true; + } + } else { + if (maxFloor != null && maxFloor <= 8) { + if (floor != null && floor <= 6) { + flag = false; + } else { + flag = true; + } + } else { + flag = false; + } + } + } + } else { + if (maxFloor != null && maxFloor <= 5) { + if (floor != null && floor <= 4) { + if (floor != null && floor <= 3) { + if (floor != null && floor <= 1) { + flag = false; + } else { + flag = true; + } + } else { + flag = false; + } + } else { + flag = true; + } + } else { + if (maxFloor != null && maxFloor <= 10) { + if (maxFloor != null && maxFloor <= 6) { + if (size != null && size <= 223) { + if (floor != null && floor <= 1) { + flag = false; + } else { + if (size != null && size <= 206) { + flag = false; + } else { + if (size != null && size <= 215) { + flag = true; + } else { + flag = false; + } + } + } + } else { + if (floor != null && floor <= 5) { + if (floor != null && floor <= 3) { + if (floor != null && floor <= 1) { + flag = false; + } else { + flag = true; + } + } else { + flag = false; + } + } else { + flag = true; + } + } + } else { + if (size != null && size <= 267) { + if (size != null && size <= 219) { + if (size != null && size <= 208) { + flag = false; + } else { + if (size != null && size <= 214) { + flag = true; + } else { + flag = false; + } + } + } else { + flag = false; + } + } else { + if (floor != null && floor <= 4) { + flag = false; + } else { + if (size != null && size <= 286) { + flag = true; + } else { + flag = false; + } + } + } + } + } else { + if (size != null && size <= 252) { + if (size != null && size <= 249) { + if (size != null && size <= 204) { + flag = true; + } else { + if (floor != null && floor <= 2) { + flag = false; + } else { + if (maxFloor != null && maxFloor <= 11) { + flag = false; + } else { + if (size != null && size <= 228) { + flag = true; + } else { + flag = false; + } + } + } + } + } else { + flag = true; + } + } else { + flag = false; + } + } + } + } + } else { + flag = false; + } + } else { + if (size != null && size <= 340) { + if (maxFloor != null && maxFloor <= 5) { + flag = true; + } else { + if (size != null && size <= 323) { + flag = true; + } else { + flag = false; + } + } + } else { + flag = true; + } + } + } + } + return flag; + } - }); - } + }); + } - private String getHouseType(com.fangjia.dal.datastore.model.House bo) { - StringBuilder sb = new StringBuilder(); - if (bo.getRoom() != null) { - sb.append(bo.getRoom() + "ÊÒ"); - } - if (bo.getHall() != null) { - sb.append(bo.getHall() + "Ìü"); - } - if (bo.getToilet() != null) { - sb.append(bo.getHall() + "ÎÀ"); - } - return sb.toString(); - } + private String getHouseType(com.fangjia.dal.datastore.model.House bo) { + StringBuilder sb = new StringBuilder(); + if (bo.getRoom() != null) { + sb.append(bo.getRoom() + "ÊÒ"); + } + if (bo.getHall() != null) { + sb.append(bo.getHall() + "Ìü"); + } + if (bo.getToilet() != null) { + sb.append(bo.getHall() + "ÎÀ"); + } + return sb.toString(); + } - private Integer getYearFormDate(String dateStr) { - if (dateStr != null && StringUtils.isNotBlank(dateStr)) { - Date date = DateUtil.parseStringToDate(dateStr); - if (date != null) { - int year = date.getYear() + 1900; - return year; - } - } - return null; - } + private Integer getYearFormDate(String dateStr) { + if (dateStr != null && StringUtils.isNotBlank(dateStr)) { + Date date = DateUtil.parseStringToDate(dateStr); + if (date != null) { + int year = date.getYear() + 1900; + return year; + } + } + return null; + } - private Integer getBuildYear(String finishDate, String liveDate, String buildDate ,Date openDate) { + private Integer getBuildYear(String finishDate, String liveDate, String buildDate, Date openDate) { - Integer finishYear = getYearFormDate(finishDate); - Integer liveYear = getYearFormDate(liveDate); - Integer buildYear = getYearFormDate(buildDate); - Integer openYear = null; - if(openDate != null){ - openYear = Integer.valueOf(DateUtil.formatByPattern(openDate,"yyyy")); - } - int minYear = Integer.MAX_VALUE; - if (finishYear != null && finishYear < minYear) { - minYear = finishYear; - } - if (liveYear != null && liveYear < minYear) { - minYear = liveYear; - } - if (buildYear != null && buildYear < minYear) { - minYear = buildYear; - } - if(openYear != null && openYear < minYear){ - minYear = openYear; - } - if(minYear == Integer.MAX_VALUE){ - return null; - } - return minYear; - } + Integer finishYear = getYearFormDate(finishDate); + Integer liveYear = getYearFormDate(liveDate); + Integer buildYear = getYearFormDate(buildDate); + Integer openYear = null; + if (openDate != null) { + openYear = Integer.valueOf(DateUtil.formatByPattern(openDate, "yyyy")); + } + int minYear = Integer.MAX_VALUE; + if (finishYear != null && finishYear < minYear) { + minYear = finishYear; + } + if (liveYear != null && liveYear < minYear) { + minYear = liveYear; + } + if (buildYear != null && buildYear < minYear) { + minYear = buildYear; + } + if (openYear != null && openYear < minYear) { + minYear = openYear; + } + if (minYear == Integer.MAX_VALUE) { + return null; + } + return minYear; + } - private Integer getHouseUseYear(Integer minYear, String s){ + private Integer getHouseUseYear(Integer minYear, String s) { - if(StringUtils.isBlank(s)){ - return null; - } - if(minYear != null && minYear > 0){ - int curYear = new Date().getYear() + 1900; - int shengYuYear = curYear - minYear; - if( shengYuYear > 0 && shengYuYear <= 70){ - Integer year = extractYear(s); - if(year !=null && year > 0 && year <= 70){ - int useYear = year - shengYuYear; - if(year > 0 && year <= 70){ - return useYear; - } + if (StringUtils.isBlank(s)) { + return null; + } + if (minYear != null && minYear > 0) { + int curYear = new Date().getYear() + 1900; + int shengYuYear = curYear - minYear; + if (shengYuYear > 0 && shengYuYear <= 70) { + Integer year = extractYear(s); + if (year != null && year > 0 && year <= 70) { + int useYear = year - shengYuYear; + if (year > 0 && year <= 70) { + return useYear; + } - } - } - } - return null; - } + } + } + } + return null; + } - private Integer extractYear(String s) { - Pattern p = Pattern.compile("(\\d+)"); - Matcher m = p.matcher(s); - if (m.find()) { - return Integer.parseInt(m.group(1)); - } - return null; - } + private Integer extractYear(String s) { + Pattern p = Pattern.compile("(\\d+)"); + Matcher m = p.matcher(s); + if (m.find()) { + return Integer.parseInt(m.group(1)); + } + return null; + } - public String getDomainName(String url) { - if (StringUtils.isNotBlank(url)) { - Pattern p = Pattern.compile("[^//]*?\\.(com|cn|net|org|biz|info|cc|tv)", Pattern.CASE_INSENSITIVE); - Matcher matcher = p.matcher(url); - if (matcher.find()) { - return matcher.group(); - } + public String getDomainName(String url) { + if (StringUtils.isNotBlank(url)) { + Pattern p = Pattern.compile("[^//]*?\\.(com|cn|net|org|biz|info|cc|tv)", Pattern.CASE_INSENSITIVE); + Matcher matcher = p.matcher(url); + if (matcher.find()) { + return matcher.group(); + } - } - return "fangjia.com"; - } + } + return "fangjia.com"; + } - /** - * аætokenÑéÖ¤ - * - * @param token - * @return - */ - private ApiUser checkNewAuthorized(String token) { - Map tokenMap = FangjiaApiUtil.parseToken(token); - if (tokenMap == null) { - return null; - } - // tokenÑéÖ¤ºó£¬ÄÃÈ¡³öµÄ×Ö¶ÎÔÙÈ¥Êý¾Ý¿âÑéÖ¤Ò»±é - if (StringUtils.isNotBlank(tokenMap.get("userid")) && !"null".equals(tokenMap.get("userid"))) { - List params = new ArrayList(); - params.add(new QueryParam("ID", tokenMap.get("userid"))); - ApiUser apiUser = apiUserService.findApiUserById(Long.parseLong(tokenMap.get("userid"))); - if (apiUser != null) { - if (tokenMap.get("appKey").equals(apiUser.getAppKey())) { - return apiUser; - } - } - } - return null; - } + /** + * аætokenÑéÖ¤ + * + * @param token + * @return + */ + private ApiUser checkNewAuthorized(String token) { + Map tokenMap = FangjiaApiUtil.parseToken(token); + if (tokenMap == null) { + return null; + } + // tokenÑéÖ¤ºó£¬ÄÃÈ¡³öµÄ×Ö¶ÎÔÙÈ¥Êý¾Ý¿âÑéÖ¤Ò»±é + if (StringUtils.isNotBlank(tokenMap.get("userid")) && !"null".equals(tokenMap.get("userid"))) { + List params = new ArrayList(); + params.add(new QueryParam("ID", tokenMap.get("userid"))); + ApiUser apiUser = apiUserService.findApiUserById(Long.parseLong(tokenMap.get("userid"))); + if (apiUser != null) { + if (tokenMap.get("appKey").equals(apiUser.getAppKey())) { + return apiUser; + } + } + } + return null; + } - public AddressParser getAddressParser() { - return addressParser; - } + public AddressParser getAddressParser() { + return addressParser; + } - public void setAddressParser(AddressParser addressParser) { - this.addressParser = addressParser; - } + public void setAddressParser(AddressParser addressParser) { + this.addressParser = addressParser; + } - public HouseService getHouseService() { - return houseService; - } + public HouseService getHouseService() { + return houseService; + } - public void setHouseService(HouseService houseService) { - this.houseService = houseService; - } + public void setHouseService(HouseService houseService) { + this.houseService = houseService; + } - public MenuService getMenuService() { - return menuService; - } + public MenuService getMenuService() { + return menuService; + } - public void setMenuService(MenuService menuService) { - this.menuService = menuService; - } + public void setMenuService(MenuService menuService) { + this.menuService = menuService; + } - public DistrictService getDistrictService() { - return districtService; - } + public DistrictService getDistrictService() { + return districtService; + } - public void setDistrictService(DistrictService districtService) { - this.districtService = districtService; - } + public void setDistrictService(DistrictService districtService) { + this.districtService = districtService; + } - public void setNoHouseDistrictService(NoHouseDistrictService noHouseDistrictService) { - this.noHouseDistrictService = noHouseDistrictService; - } + public void setNoHouseDistrictService(NoHouseDistrictService noHouseDistrictService) { + this.noHouseDistrictService = noHouseDistrictService; + } - public void setApiUserService(ApiUserService apiUserService) { - this.apiUserService = apiUserService; - } + public void setApiUserService(ApiUserService apiUserService) { + this.apiUserService = apiUserService; + } - public void setUserService(UserService userService) { - this.userService = userService; - } + public void setUserService(UserService userService) { + this.userService = userService; + } - public void setDistrictStatService(DistrictStatService districtStatService) { - this.districtStatService = districtStatService; - } + public void setDistrictStatService(DistrictStatService districtStatService) { + this.districtStatService = districtStatService; + } - public void setDistrictFacilitysService(DistrictFacilitysService districtFacilitysService) { - this.districtFacilitysService = districtFacilitysService; - } + public void setDistrictFacilitysService(DistrictFacilitysService districtFacilitysService) { + this.districtFacilitysService = districtFacilitysService; + } - public void setDealPriceService(DealPriceService dealPriceService) { - } + public void setDealPriceService(DealPriceService dealPriceService) { + } - public void setMetroService(MetroService metroService) { - this.metroService = metroService; - } + public void setMetroService(MetroService metroService) { + this.metroService = metroService; + } - public static String getEstateType(String code) { - for (Map.Entry entry : ESTATE_TYPE_CODE.entrySet()) { - if (entry.getValue().equals(code)) { - return entry.getKey(); - } - } - return null; - } + public static String getEstateType(String code) { + for (Map.Entry entry : ESTATE_TYPE_CODE.entrySet()) { + if (entry.getValue().equals(code)) { + return entry.getKey(); + } + } + return null; + } - public static String getBulidType(String code) { - for (Map.Entry entry : BULIDS_TYPE_CODE.entrySet()) { - if (entry.getValue().equals(code)) { - return entry.getKey(); - } - } - return null; - } + public static String getBulidType(String code) { + for (Map.Entry entry : BULIDS_TYPE_CODE.entrySet()) { + if (entry.getValue().equals(code)) { + return entry.getKey(); + } + } + return null; + } - public void setStatsIndexService(StatsIndexService statsIndexService) { - this.statsIndexService = statsIndexService; - } + public void setStatsIndexService(StatsIndexService statsIndexService) { + this.statsIndexService = statsIndexService; + } - private Integer getRemainUseYear(District district) { - if("ËÕÖÝ".equals(district.getCity())){ - if("ÉÌס".equals(district.getEstateType2())){ - district.setPropertyLife("47"); - }else{ - district.setPropertyLife("67"); - } - } - if (district.getBuildDate() != null || district.getFinishBuildingDate() != null || district.getLiveDate() != null || district.getOpenDate() != null) { - Integer minYear = getBuildYear(district.getFinishBuildingDate(), district.getLiveDate(), district.getBuildDate(), district.getOpenDate()); - Integer useYear = getHouseUseYear(minYear, district.getPropertyLife()); - if (useYear != null && useYear > 0 && useYear < 70) { - return useYear; - } - } - return null; - } + private Integer getRemainUseYear(District district) { + if ("ËÕÖÝ".equals(district.getCity())) { + if ("ÉÌס".equals(district.getEstateType2())) { + district.setPropertyLife("47"); + } else { + district.setPropertyLife("67"); + } + } + if (district.getBuildDate() != null || district.getFinishBuildingDate() != null || district.getLiveDate() != null || district.getOpenDate() != null) { + Integer minYear = getBuildYear(district.getFinishBuildingDate(), district.getLiveDate(), district.getBuildDate(), district.getOpenDate()); + Integer useYear = getHouseUseYear(minYear, district.getPropertyLife()); + if (useYear != null && useYear > 0 && useYear < 70) { + return useYear; + } + } + return null; + } - public void setCzbankSampleService(CzbankSampleService czbankSampleService) { - this.czbankSampleService = czbankSampleService; - } + public void setCzbankSampleService(CzbankSampleService czbankSampleService) { + this.czbankSampleService = czbankSampleService; + } - public void setFangjiaOfficialAreaService(FangjiaOfficialAreaService fangjiaOfficialAreaService) { - this.fangjiaOfficialAreaService = fangjiaOfficialAreaService; - } + public void setFangjiaOfficialAreaService(FangjiaOfficialAreaService fangjiaOfficialAreaService) { + this.fangjiaOfficialAreaService = fangjiaOfficialAreaService; + } + public void setSeaweedService(SeaweedService seaweedService) { + this.seaweedService = seaweedService; + } + + public void setRentHouseService(RentHouseService rentHouseService) { + this.rentHouseService = rentHouseService; + } } diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/PropertyController.java b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/PropertyController.java index ae8b64282..89ee1cfcf 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/PropertyController.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/PropertyController.java @@ -6,6 +6,7 @@ import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; +import java.math.BigDecimal; import java.net.URLEncoder; import java.nio.charset.Charset; import java.text.ParseException; @@ -178,7 +179,10 @@ public class PropertyController { private FileDao fileDao = FileDao.getInstance(); private static final int DEFAULT_PAGE_SIZE = 20; + private static final int DEFAULT_HOUSE_COUNT = 5; private static final String[] PROPERTY_SEARCH_API_FIELDS = {"address", "city", "region", "name", "lat2", "lng2", "lat", "lng", "block", "estateType2", "addrAlias", "alias"}; + + private static final List GAODE_LEVEL = Arrays.asList("ÐËȤµã", "ÃÅÅÆºÅ", "µ¥ÔªºÅ", "Â¥²ã", "·¿¼ä", "ÃÅÖ·", "×¡Õ¬Çø"); static final int BAI_DU_GEO = 1;// °Ù¶ÈÏµ×ø±ê static final int GAO_DE_GEO = 2;// ¸ßµÂÏµ×ø±ê @@ -748,7 +752,9 @@ public class PropertyController { districtInfoDto.setDistrict(district.getRegion()); districtInfoDto.setName(district.getName()); districtInfoDto.setAddress(district.getAddress()); - int avgPrice = districtStatService.findLatestDistrictAvgPrice(new DistrictKey(district), null); + //int avgPrice = districtStatService.findLatestDistrictAvgPrice(new DistrictKey(district), null); + // ·µ»Ø2B¼Û¸ñ£¬Ð¡³ÌÐòÓã¬ÆäËûÒ²¸ÄΪ2B + int avgPrice = districtStatService.findLatestDistrictAvgPrice2B(new DistrictKey(district), null); if (avgPrice != 0) { districtInfoDto.setAvgPrice(avgPrice); } @@ -1051,7 +1057,8 @@ public class PropertyController { RestfulModelAndView mav = new RestfulModelAndView(); mav.setViewType("rest"); if (StringUtils.isBlank(model.getCity()) || StringUtils.isBlank(model.getName()) - || StringUtils.isBlank(model.getDistrict()) || model.getSize() <= 0) { + || StringUtils.isBlank(model.getDistrict()) || model.getSize() <= 0 || model.getCity().contains("È«¹ú") + || model.getDistrict().contains("È«¹ú")) { mav.setModel(BasicModel.buildBadRequestModel("²ÎÊý·Ç·¨:³ÇÊÐ,ÇøÓò,Ð¡ÇøÃû,Ãæ»ý(size)Ϊ±ØÌîÏî")); return mav; } @@ -1602,6 +1609,7 @@ public class PropertyController { params.put("suggestName", model.getName()); } params.put("category", "district"); + params.put("propertyType", model.getPropertyType()); String result = addressMatchProxyService.parser(params); if (result != null) { JSONObject json = JSONObject.fromObject(result); @@ -1609,6 +1617,11 @@ public class PropertyController { Map map = (Map) json.get("result"); if ((Integer) map.get("precise") >= 0) { String propertyType = (String) map.get("propertyType"); + // ÓÅÏÈʹÓÿͻ§µÄÎïÒµÀàÐÍ£¬¼´Ê¹Ãæ»ýºÜ´óÒ²²»½øÐбðÊûÍÆ¶Ï 20241111 + String userPropertyTypeParam = model.getPropertyType(); + if (StringUtils.isNotBlank(userPropertyTypeParam) && ("0,2".contains(userPropertyTypeParam))) { + villaFlag = false; + } if (villaFlag && StringUtils.isNotBlank(propertyType) && !propertyType.equals("±ðÊû")) { district = districtService.findByNameAndAlias((String) map.get("city"), (String) map.get("district"), (String) map.get("name") + "±ðÊû", "district"); } @@ -1621,7 +1634,32 @@ public class PropertyController { } if (district == null) { - mav.setModel(BasicModel.buildBadRequestModel("¸ÃµØÖ·²»Ö§³Ö¹À¼Û£¡")); + //¼ÓÉϸߵ»ñÈ¡¾­Î³¶È ºÍ ¸ù¾Ý¾­Î³¶È¹ÀÖµ + Map map = GeoUtils.parserByGaode(model.getCity(), model.getAddress()); + if (map.containsKey("level") && GAODE_LEVEL.contains(map.get("level")) + && map.containsKey("lng") && map.containsKey("lat")) { + String location = map.get("lng") + "," + map.get("lat"); + HttpRequest httpRequest = new HttpRequest(); + JSONObject json = null; + Map param = new HashMap(); + param.put("location", location); + param.put("area", String.valueOf(model.getSize())); + try { + json = httpRequest.getJsonContent("http://192.168.0.100:30020/avmWeb/avmAnn", param, "UTF-8"); + if (json.containsKey("msg") && "³É¹¦".equals(json.getString("msg"))) { + HashMap resultMap = new HashMap(); + resultMap.put("avgPrice",json.getString("unitPrice")); + resultMap.put("totalPrice",json.getString("totalPrice")); + mav.setModel(BasicModel.buildOKModel().setResult(resultMap)); + } else { + mav.setModel(BasicModel.buildBadRequestModel("¸ÃµØÖ·²»Ö§³Ö¹À¼Û£¡")); + } + } catch (HttpRequestException e) { + throw new RuntimeException(e); + } + } else { + mav.setModel(BasicModel.buildBadRequestModel("¸ÃµØÖ·²»Ö§³Ö¹À¼Û£¡")); + } return mav; } model.setDistrict(district.getRegion()); @@ -2391,7 +2429,7 @@ public class PropertyController { item.put("city", districtStat.getCity()); item.put("district", districtStat.getRegion()); item.put("name", districtStat.getDistrictName()); - item.put("avgPrice", districtStat.getAvgPrice()); + item.put("avgPrice", districtStat.getAvg_price_2b()); if ("monthly".equals(model.getPeriodType())) { item.put("date", DateUtil.formatByPattern(districtStat.getWeekend(), "yyyy-MM")); } else { @@ -2507,7 +2545,7 @@ public class PropertyController { } Date startDate = DateUtil.add(new Date(), Calendar.MONTH, -model.getPeriodCount()); - List sqmetreRents = sqmetreRentService.findSqmetreRents(RegionData.formatCity(model.getCity()), RegionData.formatRegion(model.getCity(),model.getDistrict()), model.getName(), model.getCat(), startDate, null); + List sqmetreRents = sqmetreRentService.findSqmetreRents(RegionData.formatCity(model.getCity()), RegionData.formatRegion(model.getCity(), model.getDistrict()), model.getName(), model.getCat(), startDate, null); List> result = new ArrayList>(model.getPeriodCount()); for (SqmetreRent sqmetreRent : sqmetreRents) { @@ -2780,7 +2818,7 @@ public class PropertyController { return mav; } if (model.getMax() == null || model.getMax() < 1) { - model.setMax(DEFAULT_PAGE_SIZE); + model.setMax(DEFAULT_HOUSE_COUNT); } else if (model.getMax() > 100) { model.setMax(100); } @@ -5844,7 +5882,8 @@ public class PropertyController { districtPriceMap.put("name", district.getName()); districtPriceMap.put("address", district.getAddress()); districtPriceMap.put("totalPrice", evaluation.getTotalPrice()); - districtPriceMap.put("cal_date", model.getCalDate()); + //districtPriceMap.put("cal_date", model.getCalDate()); + districtPriceMap.put("unitPrice", new BigDecimal(evaluation.getTotalPrice() / evaluation.getArea()).setScale(0, BigDecimal.ROUND_HALF_UP).intValue()); mav.setModel(BasicModel.buildOKModel().setResult(districtPriceMap)); return mav; } else { diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/StatsIndexController.java b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/StatsIndexController.java index 68d977495..5e2514098 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/StatsIndexController.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/StatsIndexController.java @@ -5,7 +5,13 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import com.fangjia.dal.mongo.model.FangjiaOfficialAreaMap; +import com.fangjia.dal.mongo.model.PropertyStatsIndex; +import com.fangjia.dal.seaweed.model.District; import com.fangjia.open.model.BasicModel; +import com.fangjia.service.datastore.DistrictService; +import com.fangjia.service.mongo.fangjia.PropertyStatsIndexService; +import com.fangjia.service.open.FangjiaOfficialAreaService; import org.apache.commons.lang.StringUtils; import com.fangjia.core.util.DistrictCodeUtils; @@ -22,380 +28,453 @@ import com.fangjia.service.bo.IndexBo; import com.fangjia.service.bo.LandPriceIndexBo; import com.fangjia.service.mongo.fangjia.LandPriceIndexService; import com.fangjia.service.mongo.fangjia.StatsIndexService; +import org.sothis.core.util.CollectionUtils; public class StatsIndexController { - private StatsIndexService statsIndexService; - private LandPriceIndexService landPriceIndexService; + private StatsIndexService statsIndexService; + private LandPriceIndexService landPriceIndexService; - /** - *²éѯ - * param y:city : ,yearmonth: yyyyMM cat:ÉÌÆÌ£¬Ð´×ÖÂ¥£¬×¡Õ¬ - */ - @Authority(role = Role.USER) - public Object searchAction(StatsIndexModel model) throws Exception { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if(StringUtils.isBlank(model.getCity())){ - mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "ÇëÊäÈë³ÇÊбàÂë")); - return mav; - } - String cityName = DistrictCodeUtils.getCityName(model.getCity()); - if(cityName == null){ - mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "ÎÞ·¨Æ¥Åäµ½¸Ã³ÇÊбàÂë")); - return mav; - } - if (StringUtils.isBlank(model.getYearmonth())) { - mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "ÇëÊäÈëÒª²éѯµÄÄêÔÂ")); - return mav; - } - Map resMap = new HashMap(); - List statsIndexs=statsIndexService.findAllStats(model.getCity(), model.getYearmonth(), true,model.getCat()); - List statsIndexList=new ArrayList(); - if("ÉÌÆÌ".equalsIgnoreCase(model.getCat()) || "д×ÖÂ¥".equalsIgnoreCase(model.getCat())){ - for(StatsIndex statsIndex:statsIndexs){ - StatsIndex newStatsIndex=new StatsIndex(); - newStatsIndex.setFangChain(statsIndex.getFangChain()); - newStatsIndex.setFangIndex(statsIndex.getFangIndex()); - newStatsIndex.setCity(DistrictCodeUtils.getCityCode(statsIndex.getCity())); - newStatsIndex.setYearmonth(statsIndex.getYearmonth()); - if(StringUtils.isNotBlank(newStatsIndex.getCity())){ - statsIndexList.add(newStatsIndex); - } - } - }else{ - for(StatsIndex statsIndex:statsIndexs){ - StatsIndex newStatsIndex=new StatsIndex(); - newStatsIndex.setNewChain(statsIndex.getNewChain()); - newStatsIndex.setNewYeartoyear(statsIndex.getNewYeartoyear()); - newStatsIndex.setNewFixedbase(statsIndex.getNewFixedbase()); - - newStatsIndex.setBelowChain(statsIndex.getBelowChain()); - newStatsIndex.setBelowYeartoyear(statsIndex.getBelowYeartoyear()); - newStatsIndex.setBelowFixedbase(statsIndex.getBelowFixedbase()); - - newStatsIndex.setAmongChain(statsIndex.getAmongChain()); - newStatsIndex.setAmongYeartoyear(statsIndex.getAmongYeartoyear()); - newStatsIndex.setAmongFixedbase(statsIndex.getAmongFixedbase()); - - newStatsIndex.setAboveChain(statsIndex.getAboveChain()); - newStatsIndex.setAboveYeartoyear(statsIndex.getAboveYeartoyear()); - newStatsIndex.setAboveFixedbase(statsIndex.getAboveFixedbase()); - - newStatsIndex.setCity(DistrictCodeUtils.getCityCode(statsIndex.getCity())); - newStatsIndex.setYearmonth(String.valueOf(statsIndex.getSource())); - if(StringUtils.isNotBlank(newStatsIndex.getCity())){ - statsIndexList.add(newStatsIndex); - } - } - } - if(statsIndexList.isEmpty()){ - mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "Çë¼ì²éÊäÈëµÄ³ÇÊлòÕßÄêÔÂ")); - return mav; - } - resMap.put("results",statsIndexList.get(0)); - if(statsIndexList.size()>0){ - resMap.put("count", statsIndexList.size()); - if("ÉÌÆÌ".equals(model.getCat())){ - resMap.put("type", "ÉÌÆÌ"); - }else if("д×ÖÂ¥".equals(model.getCat())){ - resMap.put("type", "д×ÖÂ¥"); - }else{ - resMap.put("type", "סլ"); - } - } - mav.setModel(resMap); - return mav; - } + private FangjiaOfficialAreaService fangjiaOfficialAreaService; + private DistrictService districtService; - /** - *²éѯз¿Ö¸Êý - * param yearmonth: yyyyMM - */ - @Authority(role = Role.USER) - public Object searchNewDistrictIndexAction(StatsIndexModel model) throws Exception { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if(StringUtils.isNotBlank(model.getCity())){ - String cityName = DistrictCodeUtils.getCityName(model.getCity()); - if(cityName == null){ - mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "ÎÞ·¨Æ¥Åäµ½¸Ã³ÇÊбàÂë")); - return mav; - } - model.setCity(cityName); - } - if(StringUtils.isBlank(model.getYearmonth())){ - mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "ÄêÔ±ØÐëÊäÈë,¸ñʽ:yyyyMM")); - return mav; - } - List statsIndexs = statsIndexService.findAllStats(model.getCity(), model.getYearmonth(), false, "סլ"); - List statsIndexList = new ArrayList(); - - if(statsIndexs != null && statsIndexs.size() > 0){ - for(StatsIndex statsIndex : statsIndexs){ - IndexBo newStatsIndex = new IndexBo(); - newStatsIndex.setCity(DistrictCodeUtils.getCityCode(statsIndex.getCity())); - newStatsIndex.setYearmonth(statsIndex.getYearmonth()); - newStatsIndex.setMOM(statsIndex.getNewChain()); - newStatsIndex.setYOY(statsIndex.getNewYeartoyear()); - newStatsIndex.setFixedBase(statsIndex.getNewFixedbase()); - newStatsIndex.setSource(String.valueOf(statsIndex.getSource())); - if(StringUtils.isNotBlank(newStatsIndex.getCity())){ - statsIndexList.add(newStatsIndex); - } - } - } - - if(statsIndexList.isEmpty()){ - mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "Ä¿±êÊý¾Ý²»´æÔÚ")); - return mav; - } - - Map resMap = new HashMap(); - resMap.put("results",statsIndexList); - resMap.put("count", statsIndexList.size()); - resMap.put("type", "н¨ÉÌÆ··¿"); - mav.setModel(resMap); - return mav; - } - - /** - *²éѯ¶þÊÖ·¿Ö¸Êý - * param yearmonth: yyyyMM - */ - @Authority(role = Role.USER) - public Object searchDistrictIndexAction(StatsIndexModel model) throws Exception { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if(StringUtils.isNotBlank(model.getCity())){ - String cityName = DistrictCodeUtils.getCityName(model.getCity()); - if(cityName == null){ - mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "ÎÞ·¨Æ¥Åäµ½¸Ã³ÇÊбàÂë")); - return mav; - } - model.setCity(cityName); - } - if(StringUtils.isBlank(model.getYearmonth())){ - mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "ÄêÔ±ØÐëÊäÈë,¸ñʽ:yyyyMM")); - return mav; - } - List statsIndexs = statsIndexService.findAllStats(model.getCity(), model.getYearmonth(), false, "סլ"); - List statsIndexList = new ArrayList(); - - if(statsIndexs != null && statsIndexs.size() > 0){ - for(StatsIndex statsIndex:statsIndexs){ - IndexBo newStatsIndex = new IndexBo(); - newStatsIndex.setSmallMOM(statsIndex.getBelowChain()); - newStatsIndex.setSmallYOY(statsIndex.getBelowYeartoyear()); - newStatsIndex.setSmallFixedBase(statsIndex.getBelowFixedbase()); - - newStatsIndex.setMediumMOM(statsIndex.getAmongChain()); - newStatsIndex.setMediumYOY(statsIndex.getAmongYeartoyear()); - newStatsIndex.setMediumFixedBase(statsIndex.getAmongFixedbase()); - - newStatsIndex.setLargeMOM(statsIndex.getAboveChain()); - newStatsIndex.setLargeYOY(statsIndex.getAboveYeartoyear()); - newStatsIndex.setLargeFixedBase(statsIndex.getAboveFixedbase()); - - newStatsIndex.setCity(DistrictCodeUtils.getCityCode(statsIndex.getCity())); - newStatsIndex.setYearmonth(statsIndex.getYearmonth()); - newStatsIndex.setSource(String.valueOf(statsIndex.getSource())); - if(StringUtils.isNotBlank(newStatsIndex.getCity())){ - statsIndexList.add(newStatsIndex); - }else{ - System.out.println(statsIndex.getCity()); - } - } - } - - if(statsIndexList.isEmpty()){ - mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "Ä¿±êÊý¾Ý²»´æÔÚ")); - return mav; - } - - Map resMap = new HashMap(); - resMap.put("results",statsIndexList); - resMap.put("count", statsIndexList.size()); - resMap.put("type", "¶þÊÖסլ"); - mav.setModel(resMap); - return mav; - } - - /** - *²éѯÉÌÆÌÖ¸Êý - * param yearmonth: yyyyMM - */ - @Authority(role = Role.USER) - public Object searchShopIndexAction(StatsIndexModel model) throws Exception { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if(StringUtils.isNotBlank(model.getCity())){ - String cityName = DistrictCodeUtils.getCityName(model.getCity()); - if(cityName == null){ - mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "ÎÞ·¨Æ¥Åäµ½¸Ã³ÇÊбàÂë")); - return mav; - } - model.setCity(cityName); - } - if(StringUtils.isBlank(model.getYearmonth())){ - mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "ÄêÔ±ØÐëÊäÈë,¸ñʽ:yyyyMM")); - return mav; - } - List statsIndexs = statsIndexService.findAllStats(model.getCity(), model.getYearmonth(), true, "ÉÌÆÌ"); - List statsIndexList = new ArrayList(); - - if(statsIndexs != null && statsIndexs.size() > 0){ - for(StatsIndex statsIndex:statsIndexs){ - IndexBo newStatsIndex = new IndexBo(); - newStatsIndex.setMOM(statsIndex.getFangChain()); - newStatsIndex.setIndex(statsIndex.getFangIndex()); - newStatsIndex.setCity(DistrictCodeUtils.getCityCode(statsIndex.getCity())); - newStatsIndex.setYearmonth(statsIndex.getYearmonth()); - newStatsIndex.setSource(String.valueOf(statsIndex.getSource())); - if(StringUtils.isNotBlank(newStatsIndex.getCity())){ - statsIndexList.add(newStatsIndex); - } - } - } - - if(statsIndexList.isEmpty()){ - mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "Ä¿±êÊý¾Ý²»´æÔÚ")); - return mav; - } - - Map resMap = new HashMap(); - resMap.put("results",statsIndexList); - resMap.put("count", statsIndexList.size()); - resMap.put("type", "ÉÌÆÌ"); - mav.setModel(resMap); - return mav; - } - - /** - *²éѯд×ÖÂ¥Ö¸Êý - * yearmonth: yyyyMM - */ - @Authority(role = Role.USER) - public Object searchOfficeIndexAction(StatsIndexModel model) throws Exception { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if(StringUtils.isNotBlank(model.getCity())){ - String cityName = DistrictCodeUtils.getCityName(model.getCity()); - if(cityName == null){ - mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "ÎÞ·¨Æ¥Åäµ½¸Ã³ÇÊбàÂë")); - return mav; - } - model.setCity(cityName); - } - if(StringUtils.isBlank(model.getYearmonth())){ - mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "ÄêÔ±ØÐëÊäÈë,¸ñʽ:yyyyMM")); - return mav; - } - - List statsIndexs=statsIndexService.findAllStats(model.getCity(), model.getYearmonth(), true, "д×ÖÂ¥"); - List statsIndexList = new ArrayList(); - - if(statsIndexs != null && statsIndexs.size() > 0){ - for(StatsIndex statsIndex:statsIndexs){ - IndexBo newStatsIndex = new IndexBo(); - newStatsIndex.setMOM(statsIndex.getFangChain()); - newStatsIndex.setIndex(statsIndex.getFangIndex()); - newStatsIndex.setCity(DistrictCodeUtils.getCityCode(statsIndex.getCity())); - newStatsIndex.setYearmonth(statsIndex.getYearmonth()); - newStatsIndex.setSource(String.valueOf(statsIndex.getSource())); - if(StringUtils.isNotBlank(newStatsIndex.getCity())){ - statsIndexList.add(newStatsIndex); - } - } - } - - if(statsIndexList.isEmpty()){ - mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "Ä¿±êÊý¾Ý²»´æÔÚ")); - return mav; - } - - Map resMap = new HashMap(); - resMap.put("results",statsIndexList); - resMap.put("count", statsIndexList.size()); - resMap.put("type", "д×ÖÂ¥"); - mav.setModel(resMap); - return mav; - } - - /** - *²éѯ - * param city:³ÇÊÐ , year:Äê·Ý - */ - @Authority(role = Role.USER) - public Object searchLandIndexAction(LandPriceIndexModel model) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if(StringUtils.isNotBlank(model.getCity())) { - String cityName = DistrictCodeUtils.getCityName(model.getCity()); - if(cityName == null){ - mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "ÎÞ·¨Æ¥Åäµ½¸Ã³ÇÊбàÂë")); - return mav; - } - model.setCity(cityName); - } - if(model.getYear() <= 0){ - mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "Äê·Ý±ØÐëÊäÈë,¸ñʽ:yyyy")); - return mav; - } - List landPriceIndexList = new ArrayList(); - if(StringUtils.isNotBlank(model.getCity())) { - landPriceIndexList = landPriceIndexService.findByCityAndYear(model.getCity(), model.getYear()); - } else { - landPriceIndexList = landPriceIndexService.findAllByYear(model.getYear()); - } - List landPriceIndexBoList = new ArrayList(); - - if(landPriceIndexList != null && landPriceIndexList.size() > 0){ - for(LandPriceIndex landPriceIndex:landPriceIndexList){ - LandPriceIndexBo landPriceIndexBo = new LandPriceIndexBo(); - - landPriceIndexBo.setCity(DistrictCodeUtils.getCityCode(landPriceIndex.getCity())); - landPriceIndexBo.setYear(landPriceIndex.getYear()); - landPriceIndexBo.setCompositeIndex(landPriceIndex.getComprehensiveIndex()); - landPriceIndexBo.setCommercialIndex(landPriceIndex.getCommercialIndex()); - landPriceIndexBo.setResidentialIndex(landPriceIndex.getDistrictIndex()); - landPriceIndexBo.setIndustrialIndex(landPriceIndex.getIndustryIndex()); - - if(StringUtils.isNotBlank(landPriceIndexBo.getCity())){ - landPriceIndexBoList.add(landPriceIndexBo); - } - } - } - - if(landPriceIndexBoList.isEmpty()){ - mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "Ä¿±êÊý¾Ý²»´æÔÚ")); - return mav; - } - - Map resMap = new HashMap(); - resMap.put("results",landPriceIndexBoList); - resMap.put("count", landPriceIndexBoList.size()); - resMap.put("type", "ÍÁµØ"); - mav.setModel(resMap); - return mav; - } - - private String getSourceString(int source){ - if(source == 1){ - return "ͳ¼Æ¾Ö"; - }else if(source == 2){ - return "·¿¼ÛÍø"; - }else if(source == 3){ - return "ÊÖ¹¤ÊäÈë"; - } - return ""; - } - - public void setStatsIndexService(StatsIndexService statsIndexService) { - this.statsIndexService = statsIndexService; - } + private PropertyStatsIndexService propertyStatsIndexService; - public void setLandPriceIndexService(LandPriceIndexService landPriceIndexService) { - this.landPriceIndexService = landPriceIndexService; - } + /** + * ²éѯ³ÇÊм¶±ð¼Û¸ñÖ¸Êý + * param y:city : ,yearmonth: yyyyMM cat:ÉÌÆÌ£¬Ð´×ÖÂ¥£¬×¡Õ¬ + */ + @Authority(role = Role.USER) + public Object cityAction(StatsIndexModel model) throws Exception { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isBlank(model.getCity())) { + mav.setModel(BasicModel.buildBadRequestModel("ÇëÊäÈë³ÇÊбàÂë")); + return mav; + } + if (null == model.getYearmonth()) { + mav.setModel(BasicModel.buildBadRequestModel("ÇëÊäÈëÒª²éѯµÄÄêÔÂ")); + return mav; + } + String cityName = DistrictCodeUtils.getCityName(model.getCity()); + if (cityName == null) { + mav.setModel(BasicModel.buildBadRequestModel("ÎÞ·¨Æ¥Åäµ½¸Ã³ÇÊбàÂë")); + return mav; + } + Map resMap = new HashMap(); + StatsIndex statsIndex = statsIndexService.findStatsIndex(cityName, "", "³ÇÊÐ", "", model.getYearmonth(), model.getCat()); + if (statsIndex != null) { + StatsIndex newStatsIndex = new StatsIndex(); + newStatsIndex.setChain(statsIndex.getChain()); + newStatsIndex.setYeartoyear(statsIndex.getYeartoyear()); + newStatsIndex.setFixedbase(statsIndex.getFixedbase()); + newStatsIndex.setBelowChain(statsIndex.getBelowChain()); + newStatsIndex.setBelowYeartoyear(statsIndex.getBelowYeartoyear()); + newStatsIndex.setBelowFixedbase(statsIndex.getBelowFixedbase()); + + newStatsIndex.setAmongChain(statsIndex.getAmongChain()); + newStatsIndex.setAmongYeartoyear(statsIndex.getAmongYeartoyear()); + newStatsIndex.setAmongFixedbase(statsIndex.getAmongFixedbase()); + + newStatsIndex.setAboveChain(statsIndex.getAboveChain()); + newStatsIndex.setAboveYeartoyear(statsIndex.getAboveYeartoyear()); + newStatsIndex.setAboveFixedbase(statsIndex.getAboveFixedbase()); + + newStatsIndex.setCity(DistrictCodeUtils.getCityCode(statsIndex.getCity())); + newStatsIndex.setYearmonth(model.getYearmonth()); + resMap.put("results", newStatsIndex); + } + resMap.put("status", "200"); + resMap.put("msg", "ok"); + mav.setModel(resMap); + return mav; + } + + /** + * ²éÑ¯ÇøÓò¼¶±ð¼Û¸ñÖ¸Êý + * + * @param model + * @return + * @throws Exception + */ + + @Authority(role = Role.USER) + public Object districtAction(StatsIndexModel model) throws Exception { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isBlank(model.getDistrict())) { + mav.setModel(BasicModel.buildBadRequestModel("ÇëÊäÈëÇøÓò±àÂë")); + return mav; + } + if (null == model.getYearmonth()) { + mav.setModel(BasicModel.buildBadRequestModel("ÇëÊäÈëÒª²éѯµÄÄêÔÂ")); + return mav; + } + FangjiaOfficialAreaMap fangjiaOfficialAreaMap = fangjiaOfficialAreaService.convertOfficialCodeToFangjia(model.getDistrict()); + if (fangjiaOfficialAreaMap == null) { + mav.setModel(BasicModel.buildBadRequestModel("ÎÞ·¨Æ¥Åäµ½¸ÃÇøÓò±àÂë")); + return mav; + } + Map resMap = new HashMap(); + StatsIndex statsIndex = statsIndexService.findStatsIndex(fangjiaOfficialAreaMap.getFangjiaCity(), fangjiaOfficialAreaMap.getFangjiaDistrict(), "ÇøÓò", "", model.getYearmonth(), model.getCat()); + if (statsIndex != null) { + StatsIndex newStatsIndex = new StatsIndex(); + newStatsIndex.setChain(statsIndex.getChain()); + newStatsIndex.setYeartoyear(statsIndex.getYeartoyear()); + newStatsIndex.setFixedbase(statsIndex.getFixedbase()); + newStatsIndex.setDistrict(model.getDistrict()); + newStatsIndex.setYearmonth(model.getYearmonth()); + resMap.put("results", newStatsIndex); + } + resMap.put("status", "200"); + resMap.put("msg", "ok"); + mav.setModel(resMap); + return mav; + } + + /** + * Ð¡Çø¼Û¸ñÖ¸Êý + * + * @param model + * @return + * @throws Exception + */ + @Authority(role = Role.USER) + public Object propertyAction(StatsIndexModel model) throws Exception { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isBlank(model.getId())) { + mav.setModel(BasicModel.buildBadRequestModel("ÇëÊäÈëÐ¡Çøid")); + return mav; + } + if (null == model.getYearmonth()) { + mav.setModel(BasicModel.buildBadRequestModel("ÇëÊäÈëÒª²éѯµÄÄêÔÂ")); + return mav; + } + District district = districtService.findById(model.getId()); + if (district == null) { + mav.setModel(BasicModel.buildBadRequestModel("ÎÞ·¨Æ¥Åäµ½Ð¡Çø")); + return mav; + } + Map resMap = new HashMap(); + PropertyStatsIndex statsIndex = propertyStatsIndexService.findStatsIndex(district.getCity(), district.getRegion(), district.getName(), model.getYearmonth()); + if (statsIndex != null) { + PropertyStatsIndex newStatsIndex = new PropertyStatsIndex(); + newStatsIndex.setChain(statsIndex.getChain()); + newStatsIndex.setYeartoyear(statsIndex.getYeartoyear()); + newStatsIndex.setFixedbase(statsIndex.getFixedbase()); + newStatsIndex.setDistrict(model.getDistrict()); + newStatsIndex.setYearmonth(model.getYearmonth()); + newStatsIndex.setId(model.getId()); + resMap.put("results", newStatsIndex); + } + + resMap.put("status", "200"); + resMap.put("msg", "ok"); + mav.setModel(resMap); + return mav; + } + + /** + * ²éѯз¿Ö¸Êý + * param yearmonth: yyyyMM + */ + @Authority(role = Role.USER) + public Object searchNewDistrictIndexAction(StatsIndexModel model) throws Exception { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isNotBlank(model.getCity())) { + String cityName = DistrictCodeUtils.getCityName(model.getCity()); + if (cityName == null) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "ÎÞ·¨Æ¥Åäµ½¸Ã³ÇÊбàÂë")); + return mav; + } + model.setCity(cityName); + } + if (null == model.getYearmonth()) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "ÄêÔ±ØÐëÊäÈë,¸ñʽ:yyyyMM")); + return mav; + } + List statsIndexs = statsIndexService.findAllStats(model.getCity(), model.getYearmonth(), false, "סլ"); + List statsIndexList = new ArrayList(); + + if (statsIndexs != null && statsIndexs.size() > 0) { + for (StatsIndex statsIndex : statsIndexs) { + IndexBo newStatsIndex = new IndexBo(); + newStatsIndex.setCity(DistrictCodeUtils.getCityCode(statsIndex.getCity())); + newStatsIndex.setYearmonth(statsIndex.getYearmonth().toString()); + newStatsIndex.setMOM(statsIndex.getChain()); + newStatsIndex.setYOY(statsIndex.getYeartoyear()); + newStatsIndex.setFixedBase(statsIndex.getFixedbase()); + newStatsIndex.setSource(String.valueOf(statsIndex.getSource())); + if (StringUtils.isNotBlank(newStatsIndex.getCity())) { + statsIndexList.add(newStatsIndex); + } + } + } + + if (statsIndexList.isEmpty()) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "Ä¿±êÊý¾Ý²»´æÔÚ")); + return mav; + } + + Map resMap = new HashMap(); + resMap.put("results", statsIndexList); + resMap.put("count", statsIndexList.size()); + resMap.put("type", "н¨ÉÌÆ··¿"); + mav.setModel(resMap); + return mav; + } + + /** + * ²éѯ¶þÊÖ·¿Ö¸Êý + * param yearmonth: yyyyMM + */ + @Authority(role = Role.USER) + public Object searchDistrictIndexAction(StatsIndexModel model) throws Exception { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isNotBlank(model.getCity())) { + String cityName = DistrictCodeUtils.getCityName(model.getCity()); + if (cityName == null) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "ÎÞ·¨Æ¥Åäµ½¸Ã³ÇÊбàÂë")); + return mav; + } + model.setCity(cityName); + } + if (null == model.getYearmonth()) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "ÄêÔ±ØÐëÊäÈë,¸ñʽ:yyyyMM")); + return mav; + } + List statsIndexs = statsIndexService.findAllStats(model.getCity(), model.getYearmonth(), false, "סլ"); + List statsIndexList = new ArrayList(); + + if (statsIndexs != null && statsIndexs.size() > 0) { + for (StatsIndex statsIndex : statsIndexs) { + IndexBo newStatsIndex = new IndexBo(); + newStatsIndex.setSmallMOM(statsIndex.getBelowChain()); + newStatsIndex.setSmallYOY(statsIndex.getBelowYeartoyear()); + newStatsIndex.setSmallFixedBase(statsIndex.getBelowFixedbase()); + + newStatsIndex.setMediumMOM(statsIndex.getAmongChain()); + newStatsIndex.setMediumYOY(statsIndex.getAmongYeartoyear()); + newStatsIndex.setMediumFixedBase(statsIndex.getAmongFixedbase()); + + newStatsIndex.setLargeMOM(statsIndex.getAboveChain()); + newStatsIndex.setLargeYOY(statsIndex.getAboveYeartoyear()); + newStatsIndex.setLargeFixedBase(statsIndex.getAboveFixedbase()); + + newStatsIndex.setCity(DistrictCodeUtils.getCityCode(statsIndex.getCity())); + newStatsIndex.setYearmonth(statsIndex.getYearmonth().toString()); + newStatsIndex.setSource(String.valueOf(statsIndex.getSource())); + if (StringUtils.isNotBlank(newStatsIndex.getCity())) { + statsIndexList.add(newStatsIndex); + } else { + System.out.println(statsIndex.getCity()); + } + } + } + + if (statsIndexList.isEmpty()) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "Ä¿±êÊý¾Ý²»´æÔÚ")); + return mav; + } + + Map resMap = new HashMap(); + resMap.put("results", statsIndexList); + resMap.put("count", statsIndexList.size()); + resMap.put("type", "¶þÊÖסլ"); + mav.setModel(resMap); + return mav; + } + + /** + * ²éѯÉÌÆÌÖ¸Êý + * param yearmonth: yyyyMM + */ + @Authority(role = Role.USER) + public Object searchShopIndexAction(StatsIndexModel model) throws Exception { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isNotBlank(model.getCity())) { + String cityName = DistrictCodeUtils.getCityName(model.getCity()); + if (cityName == null) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "ÎÞ·¨Æ¥Åäµ½¸Ã³ÇÊбàÂë")); + return mav; + } + model.setCity(cityName); + } + if (null == model.getYearmonth()) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "ÄêÔ±ØÐëÊäÈë,¸ñʽ:yyyyMM")); + return mav; + } + List statsIndexs = statsIndexService.findAllStats(model.getCity(), model.getYearmonth(), true, "ÉÌÆÌ"); + List statsIndexList = new ArrayList(); + + if (statsIndexs != null && statsIndexs.size() > 0) { + for (StatsIndex statsIndex : statsIndexs) { + IndexBo newStatsIndex = new IndexBo(); + newStatsIndex.setMOM(statsIndex.getFangChain()); + newStatsIndex.setIndex(statsIndex.getFangIndex()); + newStatsIndex.setCity(DistrictCodeUtils.getCityCode(statsIndex.getCity())); + newStatsIndex.setYearmonth(statsIndex.getYearmonth().toString()); + newStatsIndex.setSource(String.valueOf(statsIndex.getSource())); + if (StringUtils.isNotBlank(newStatsIndex.getCity())) { + statsIndexList.add(newStatsIndex); + } + } + } + + if (statsIndexList.isEmpty()) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "Ä¿±êÊý¾Ý²»´æÔÚ")); + return mav; + } + + Map resMap = new HashMap(); + resMap.put("results", statsIndexList); + resMap.put("count", statsIndexList.size()); + resMap.put("type", "ÉÌÆÌ"); + mav.setModel(resMap); + return mav; + } + + /** + * ²éѯд×ÖÂ¥Ö¸Êý + * yearmonth: yyyyMM + */ + @Authority(role = Role.USER) + public Object searchOfficeIndexAction(StatsIndexModel model) throws Exception { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isNotBlank(model.getCity())) { + String cityName = DistrictCodeUtils.getCityName(model.getCity()); + if (cityName == null) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "ÎÞ·¨Æ¥Åäµ½¸Ã³ÇÊбàÂë")); + return mav; + } + model.setCity(cityName); + } + if (null == model.getYearmonth()) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "ÄêÔ±ØÐëÊäÈë,¸ñʽ:yyyyMM")); + return mav; + } + + List statsIndexs = statsIndexService.findAllStats(model.getCity(), model.getYearmonth(), true, "д×ÖÂ¥"); + List statsIndexList = new ArrayList(); + + if (statsIndexs != null && statsIndexs.size() > 0) { + for (StatsIndex statsIndex : statsIndexs) { + IndexBo newStatsIndex = new IndexBo(); + newStatsIndex.setMOM(statsIndex.getFangChain()); + newStatsIndex.setIndex(statsIndex.getFangIndex()); + newStatsIndex.setCity(DistrictCodeUtils.getCityCode(statsIndex.getCity())); + newStatsIndex.setYearmonth(statsIndex.getYearmonth().toString()); + newStatsIndex.setSource(String.valueOf(statsIndex.getSource())); + if (StringUtils.isNotBlank(newStatsIndex.getCity())) { + statsIndexList.add(newStatsIndex); + } + } + } + + if (statsIndexList.isEmpty()) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "Ä¿±êÊý¾Ý²»´æÔÚ")); + return mav; + } + + Map resMap = new HashMap(); + resMap.put("results", statsIndexList); + resMap.put("count", statsIndexList.size()); + resMap.put("type", "д×ÖÂ¥"); + mav.setModel(resMap); + return mav; + } + + /** + * ²éѯ + * param city:³ÇÊÐ , year:Äê·Ý + */ + @Authority(role = Role.USER) + public Object searchLandIndexAction(LandPriceIndexModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isNotBlank(model.getCity())) { + String cityName = DistrictCodeUtils.getCityName(model.getCity()); + if (cityName == null) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "ÎÞ·¨Æ¥Åäµ½¸Ã³ÇÊбàÂë")); + return mav; + } + model.setCity(cityName); + } + if (model.getYear() <= 0) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "Äê·Ý±ØÐëÊäÈë,¸ñʽ:yyyy")); + return mav; + } + List landPriceIndexList = new ArrayList(); + if (StringUtils.isNotBlank(model.getCity())) { + landPriceIndexList = landPriceIndexService.findByCityAndYear(model.getCity(), model.getYear()); + } else { + landPriceIndexList = landPriceIndexService.findAllByYear(model.getYear()); + } + List landPriceIndexBoList = new ArrayList(); + + if (landPriceIndexList != null && landPriceIndexList.size() > 0) { + for (LandPriceIndex landPriceIndex : landPriceIndexList) { + LandPriceIndexBo landPriceIndexBo = new LandPriceIndexBo(); + + landPriceIndexBo.setCity(DistrictCodeUtils.getCityCode(landPriceIndex.getCity())); + landPriceIndexBo.setYear(landPriceIndex.getYear()); + landPriceIndexBo.setCompositeIndex(landPriceIndex.getComprehensiveIndex()); + landPriceIndexBo.setCommercialIndex(landPriceIndex.getCommercialIndex()); + landPriceIndexBo.setResidentialIndex(landPriceIndex.getDistrictIndex()); + landPriceIndexBo.setIndustrialIndex(landPriceIndex.getIndustryIndex()); + + if (StringUtils.isNotBlank(landPriceIndexBo.getCity())) { + landPriceIndexBoList.add(landPriceIndexBo); + } + } + } + + if (landPriceIndexBoList.isEmpty()) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "Ä¿±êÊý¾Ý²»´æÔÚ")); + return mav; + } + + Map resMap = new HashMap(); + resMap.put("results", landPriceIndexBoList); + resMap.put("count", landPriceIndexBoList.size()); + resMap.put("type", "ÍÁµØ"); + mav.setModel(resMap); + return mav; + } + + private String getSourceString(int source) { + if (source == 1) { + return "ͳ¼Æ¾Ö"; + } else if (source == 2) { + return "·¿¼ÛÍø"; + } else if (source == 3) { + return "ÊÖ¹¤ÊäÈë"; + } + return ""; + } + + public void setStatsIndexService(StatsIndexService statsIndexService) { + this.statsIndexService = statsIndexService; + } + + public void setLandPriceIndexService(LandPriceIndexService landPriceIndexService) { + this.landPriceIndexService = landPriceIndexService; + } + + public void setFangjiaOfficialAreaService(FangjiaOfficialAreaService fangjiaOfficialAreaService) { + this.fangjiaOfficialAreaService = fangjiaOfficialAreaService; + } + + public void setDistrictService(DistrictService districtService) { + this.districtService = districtService; + } + + public void setPropertyStatsIndexService(PropertyStatsIndexService propertyStatsIndexService) { + this.propertyStatsIndexService = propertyStatsIndexService; + } } diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/TestController.java b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/TestController.java index 07fbed914..f58c8fd6d 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/TestController.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/TestController.java @@ -1,1608 +1,50 @@ -/* package com.fangjia.open.controllers; -import com.fangjia.core.util.*; -import com.fangjia.dal.common.DistrictKey; -import com.fangjia.dal.mongo.fangjia.model.ServerArea; -import com.fangjia.dal.mongo.model.ApiUserCfg; -import com.fangjia.dal.mongo.model.DistrictFacilitys; -import com.fangjia.dal.mongo.model.Evaluation; -import com.fangjia.dal.mongo.model.FangjiaOfficialAreaMap; -import com.fangjia.dal.mongo.model.bkoff.Loudong; -import com.fangjia.dal.mongo.open.model.ApiUserAuthority; -import com.fangjia.dal.mongo.open.model.EvaluateRatio; -import com.fangjia.dal.seaweed.model.District; -import com.fangjia.open.HttpCode; -import com.fangjia.open.OpenHttpCodeEnum; -import com.fangjia.open.dto.HouseValueInformationDto; -import com.fangjia.open.dto.UniversalDto; -import com.fangjia.open.dto.addressGovernance.MatchedBuildingDto; -import com.fangjia.open.interceptors.AuthenticationBean; -import com.fangjia.open.model.*; -import com.fangjia.open.util.CommonDtoUtils; -import com.fangjia.open.util.CommonUtils; -import com.fangjia.open.ws.query.SampleQuery; -import com.fangjia.service.api.AddressMatchProxyService; -import com.fangjia.service.api.ApiUserCfgService; -import com.fangjia.service.bo.Collateral; -import com.fangjia.service.bo.DistrictStatBo; -import com.fangjia.service.bo.Sample; -import com.fangjia.service.datastore.*; -import com.fangjia.service.datastore.bean.CollateralSampleQueryBean; -import com.fangjia.service.district.*; -import com.fangjia.service.mongo.bkoff.HouseLoudongService; -import com.fangjia.service.mongo.bkoff.LoudongService; -import com.fangjia.service.mongo.fangjia.*; -import com.fangjia.service.open.*; -import com.fangjia.service.tool.OpenLogService; -import com.fangjia.service.web.AddressService; -import net.sf.json.JSONObject; -import org.apache.commons.lang.ArrayUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang.time.DateUtils; -import org.slf4j.Logger; -import org.sothis.web.mvc.ActionContext; -import org.sothis.web.mvc.ModelAndView; +import com.fangjia.open.model.BasicModel; +import org.sothis.web.mvc.annotation.Param; -import javax.servlet.http.HttpServletRequest; -import java.text.ParseException; -import java.util.*; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; - -import static com.poseidon.util.TypeConverter.convertToString; - -*/ +import com.fangjia.open.model.RestfulModelAndView; +import java.net.Inet4Address; +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.net.SocketException; +import java.util.Enumeration; /** - * @author 13607 - * @since 2023/12/12 10:29 - *//* - - - + * Õ¾ÄÚËÑË÷controller + * + * @author liupei + */ public class TestController { - private DistrictService districtService; - private DistrictStatService districtStatService; - - private FangjiaOfficialAreaService fangjiaOfficialAreaService; - private AddressMatchProxyService addressMatchProxyService; - - private static final Logger LOGGER = LoggerFactory.getLogger(PropertyController.class); - private HouseLoudongService houseLoudongService; - private LoudongService loudongService; - private EvaluationService evaluationService; - private BatchEvaluateService batchEvaluateService; - private ApiUserAuthorityService apiUserAuthorityService; - private AverageStatisticsService averageStatisticsService; - private ServerAreaService serverAreaService; - private ApiUserCfgService apiUserCfgService; - private OpenApiLogService openApiLogService; - private EvaluateFactorService evaluateFactorService; - - private CzbankSampleService czbankSampleService; - - private DistrictFacilitysService districtFacilitysService; - - private static final int DEFAULT_PAGE_SIZE = 20; - private static final String[] PROPERTY_SEARCH_API_FIELDS = {"address", "city", "region", "name", "lat2", "lng2", "lat", "lng", "block", "estateType2", "addrAlias"}; - static final int BAI_DU_GEO = 1;// °Ù¶ÈÏµ×ø±ê - static final int GAO_DE_GEO = 2;// ¸ßµÂÏµ×ø±ê - - - private EvaluateRatioService evaluateRatioService; - - private static final int EVALUATE_SHOW_DETAIL = 1; - private static final Map PROPERTY_TYPES = new HashMap() { - { - put(null, "ÆÕͨסլ"); - put("0", "ÆÕͨסլ"); - put("1", "±ðÊû"); - put("2", "ÉÌס"); - } - }; - - private static final Map DIRECTION = new HashMap() { - { - put(null, "ÄÏ"); - put("1", "Î÷ÄÏ"); - put("2", "¶«ÄÏ"); - put("3", "ÄÏ"); - put("4", "Î÷±±"); - put("5", "¶«±±"); - put("6", "¶«"); - put("7", "Î÷"); - put("8", "±±"); - put("9", "¶«Î÷"); - put("10", "Äϱ±"); - } - }; - - private static final Map FITMENT = new HashMap() { - { - put(null, "¼ò×°"); - put("1", "ëÅ÷"); - put("2", "¼ò×°"); - put("3", "¾«×°"); - put("4", "ºÀ×°"); - } - }; - - private static final Map EVALUATION_MODEL_FITMENT = new HashMap() { - { - put(null, "¼òµ¥×°ÐÞ"); - put("¼ò×°", "¼òµ¥×°ÐÞ"); - put("ëÅ÷", "ëÅ÷"); - put("¾«×°", "¾«×°ÐÞ"); - put("ºÀ×°", "ºÀ»ª×°ÐÞ"); - } - }; - - private static final Map SIGHT = new HashMap() { - { - put(null, "Ò»°ã"); - put("1", "¾°¹Û·¿"); - put("2", "²à¾°¹Û·¿"); - put("3", "Ò»°ã"); - put("4", "²î"); - } - }; - - private static final Map NOISE = new HashMap() { - { - put(null, "ÎÞÔëÒô"); - put("0", "ÎÞÔëÒô"); - put("1", "ÔëÒô½ÏС"); - put("2", "ÔëÒô´ó"); - } - }; - private static final Map FACILITIES = new HashMap() { - { - put("0", "½¡Éí·¿"); - put("1", "ÓÎÓ¾³Ø"); - put("2", "»áËù"); - put("3", "ÍøÇò³¡"); - put("4", "Çò³¡"); - put("5", "ÆåÅÆÊÒ"); - put("6", "Í£³µ³¡"); - put("7", "ͼÊé¹Ý"); - put("8", "»î¶¯ÖÐÐÄ"); - } - }; - - private static final Map NEGATIVE_FACTOR = new HashMap() { - { - put(null, "ÎÞ"); - put("1", "ºÜ½ü"); - put("2", "½Ï½ü"); - put("3", "ÎÞ"); - } - }; - - - Map listKeyMap = new HashMap() { - { - put("school", "schools"); - put("hospital", "hospitals"); - put("bank", "banks"); - put("supermarket", "supermarkets"); - put("market", "markets"); - put("beautySalon", "beautySalons"); - put("gym", "gyms"); - put("park", "parks"); - put("bus", "buses"); - put("metro", "metros"); - put("dock", "docks"); - put("airport", "airports"); - put("trainStation", "trainStations"); - put("restaurant", "restaurants"); - put("hotel", "hotels"); - } - }; - - private static final Map CITYLEVEL_MAP = new HashMap() { - { - put("1000", "one");// Ò»Ïß - put("1500", "newOne");// ÐÂÒ»Ïß - put("2000", "two");// ¶þÏß - put("3000", "three");// ÈýÏß - put("4000", "four");// ËÄÏß - put("5000", "five");// ÎåÏß - } - }; - - - //È«¾Öjson - private JSONObject globalJson = null; - - - public Object houseValueInformationAction(HouseInfomationModel model, HttpServletRequest httpServletRequest) throws IllegalAccessException, HttpRequestException { - - HouseValueInformationDto houseValueInformation = new HouseValueInformationDto(); + public Object testIpAction(@Param(name = "city") String city, @Param(name = "keyword") String keyword) { RestfulModelAndView mav = new RestfulModelAndView(); - - if (StringUtils.isBlank(model.getAddress()) || StringUtils.isBlank(model.getCity()) || StringUtils.isBlank(String.valueOf(model.getSize()))) { - mav.setModel(BasicModel.buildBadRequestModel("³ÇÊÐ(city),µØÖ·(address),Ãæ»ý(size)Ϊ±ØÌî×Ö¶Î")); - return mav; + String ip = getLocalHostIP(); + mav.setModel(BasicModel.buildOKModel().setResult(ip)); + return mav; + } + public static String getLocalHostIP() { + /*k8sϵͳÉÏÔËÐÐʱ,ʹÓÃhostnameÇø·Ö*/ + if ("true".equalsIgnoreCase(System.getenv("ON_K8S"))) { + return System.getenv("HOSTNAME"); } - - HttpRequest httpRequest = new HttpRequest(); - - Map communityAvgPriceParams = new HashMap(); - communityAvgPriceParams.put("city", model.getCity()); - communityAvgPriceParams.put("address", model.getAddress()); - communityAvgPriceParams.put("category", model.getCategory()); - communityAvgPriceParams.put("useMap", String.valueOf(model.isUseMap())); - globalJson = httpRequest.getJsonContent("http://192.168.0.100:32080/FangJiaNlpService/match", communityAvgPriceParams, "UTF-8"); - - // ´´½¨Ïß³Ì³Ø - ExecutorService executorService = Executors.newFixedThreadPool(5); - - Future avgPriceFuture = executorService.submit(new UpdateCommunityAvgPriceCallable(globalJson, mav)); - Future> future2 = executorService.submit(new UpdateAddressValueCallable( globalJson, model, mav, httpServletRequest)); - Future future3 = executorService.submit(new UpdateHouseCaseCallable(houseValueInformation, globalJson, model, mav)); - Future future4 = executorService.submit(new UpdateSurroundingPoiCallable(houseValueInformation, globalJson, model, mav)); - + String result = null; try { - // »ñÈ¡Ïß³ÌÈÎÎñµÄ·µ»Ø½á¹û - MatchedBuildingDto avgPrice = avgPriceFuture.get(); - if (avgPrice!=null){ - houseValueInformation.setCommunityAvgPrice(avgPrice); - }else { - mav.setModel(BasicModel.buildServerErrorModel().setMsg("·þÎñÉý¼¶ÖÐ...")); + Enumeration enumeration = NetworkInterface.getNetworkInterfaces(); + InetAddress ip; + while (enumeration.hasMoreElements()) { + NetworkInterface netInterface = (NetworkInterface) enumeration.nextElement(); + Enumeration addresses = netInterface.getInetAddresses(); + while (addresses.hasMoreElements()) { + ip = (InetAddress) addresses.nextElement(); + if (ip != null && ip instanceof Inet4Address && (ip.getHostAddress().contains("192.168.0") || ip.getHostAddress().contains("192.168.10"))) { + result = ip.getHostAddress(); + } + } } - Map result2 = future2.get(); - UniversalDto result3 = future3.get(); - DistrictFacilitys result4 = future4.get(); - - // ¸ù¾ÝÐèÒª´¦Àí·µ»Ø½á¹û - // ... - } catch (Exception e) { - // ´¦ÀíÒì³£ + } catch (SocketException e) { e.printStackTrace(); } - - - // ¹Ø±ÕÏß³Ì³Ø - executorService.shutdown(); - return mav; - - - } - - private class UpdateCommunityAvgPriceCallable implements Callable { - private JSONObject globalJson; - private ModelAndView mav; - - public UpdateCommunityAvgPriceCallable( JSONObject globalJson, ModelAndView mav) { - this.globalJson = globalJson; - this.mav = mav; - } - - @Override - public MatchedBuildingDto call() throws Exception { - synchronized (globalJson) { - - try { - //ÐÂÆ¥Åä½Ó¿Ú - JSONObject json = globalJson; - BasicModel basicModel = new BasicModel(200, "ok"); - if (json != null && json.size() > 0) { - MatchedBuildingDto dto = CommonDtoUtils.transformV(MatchedBuildingDto.class, json); - - District district = districtService.findByNameAndAlias(dto.getCity(), dto.getDistrict(), dto.getName(), "district"); - if (null != district) { - DistrictStatBo statBo = districtStatService.findCurrentDistrictStat(new DistrictKey(dto.getCity(), dto.getDistrict(), dto.getName())); - if (null != statBo) { - if (statBo.getDistrictStat() != null) { - dto.setAvgPrice(statBo.getDistrictStat().getAvgPrice()); - } else if (statBo.getVillaDistrictStat() != null) { - dto.setAvgPrice(statBo.getVillaDistrictStat().getAvgPrice()); - } - - } - } -// basicModel.setResult(dto); - // ±£´æÐ¡Çø¾ù¼ÛµÄ·µ»Ø½á¹û - return dto; - } - } catch (Exception e) { - e.printStackTrace(); - return null; - } - return null; - } - } - } - - private class UpdateAddressValueCallable implements Callable { - private JSONObject globalJson; - - private HouseInfomationModel model; - - private RestfulModelAndView mav; - private HttpServletRequest httpServletRequest; - - public UpdateAddressValueCallable(JSONObject globalJson, HouseInfomationModel model, RestfulModelAndView mav, HttpServletRequest httpServletRequest) { - this.globalJson = globalJson; - this.model = model; - this.mav = mav; - this.httpServletRequest = httpServletRequest; - } - - @Override - public MatchedBuildingDto call() throws Exception { - //¸ù¾Ýmodel¸øPropertyEvaluationModel¸³Öµ - PropertyEvaluationModel propertyEvaluationModel = createPropertyEvaluationModelFromHouseInfomationModel(model); - -// RestfulModelAndView propertyEvaluationMav = new RestfulModelAndView(); -// mav.setViewType("rest"); -// if (StringUtils.isBlank(propertyEvaluationModel.getCity()) || StringUtils.isBlank(propertyEvaluationModel.getAddress()) || propertyEvaluationModel.getSize() <= 0) { -// mav.setModel(BasicModel.buildBadRequestModel("²ÎÊý·Ç·¨:³ÇÊÐ,µØÖ·,Ãæ»ý(size)Ϊ±ØÌîÏî")); -// return mav; -// } - if (propertyEvaluationModel.getDistrict() != null) { - //ÇøÓò±àÂëת·¿¼ÛÍøÇøÓò - FangjiaOfficialAreaMap fangjiaOfficialAreaMap = fangjiaOfficialAreaService.convertOfficialCodeToFangjia(propertyEvaluationModel.getDistrict()); - if (fangjiaOfficialAreaMap != null) { - propertyEvaluationModel.setDistrict(fangjiaOfficialAreaMap.getFangjiaDistrict()); - } - } - - boolean villaFlag = DataUtil.isVilla(propertyEvaluationModel.getSize(), propertyEvaluationModel.getName(), propertyEvaluationModel.getHeight(), propertyEvaluationModel.getRoom()); - - District district = null; - Map params = new HashMap(); - params.put("city", propertyEvaluationModel.getCity()); - if (StringUtils.isNotBlank(propertyEvaluationModel.getDistrict())) { - params.put("suggestDistrict", propertyEvaluationModel.getDistrict()); - } - params.put("address", propertyEvaluationModel.getAddress()); - if (StringUtils.isNotBlank(propertyEvaluationModel.getName())) { - params.put("suggestName", propertyEvaluationModel.getName()); - } - params.put("category", "district"); - String result = addressMatchProxyService.parser(params); - if (result != null) { - JSONObject json = globalJson; - json = JSONObject.fromObject(result); - if (json.getInt("code") == 200) { - Map map = (Map) json.get("result"); - if ((Integer) map.get("precise") >= 0) { - String propertyType = (String) map.get("propertyType"); - if (villaFlag && StringUtils.isNotBlank(propertyType) && !propertyType.equals("±ðÊû")) { - district = districtService.findByNameAndAlias((String) map.get("city"), (String) map.get("district"), (String) map.get("name") + "±ðÊû", "district"); - } - if (null == district) { - district = districtService.findByNameAndAlias((String) map.get("city"), (String) map.get("district"), (String) map.get("name"), "district"); - } - - } - } - } - - if (district == null) { - mav.setModel(BasicModel.buildBadRequestModel("¸ÃµØÖ·²»Ö§³Ö¹À¼Û£¡")); -// return mav; - } - propertyEvaluationModel.setDistrict(district.getRegion()); - propertyEvaluationModel.setName(district.getName()); - try { - evaluateAction(propertyEvaluationModel, httpServletRequest, mav); - } catch (IllegalAccessException e) { - throw new RuntimeException(e); - } - } - } - - private class UpdateAddressValueRunnable implements Runnable { - private HouseValueInformationDto houseValueInformation; - - private JSONObject globalJson; - - private HouseInfomationModel model; - - private RestfulModelAndView mav; - private HttpServletRequest httpServletRequest; - - public UpdateAddressValueRunnable(HouseValueInformationDto houseValueInformation, JSONObject globalJson, HouseInfomationModel model, RestfulModelAndView mav, HttpServletRequest httpServletRequest) { - this.houseValueInformation = houseValueInformation; - this.globalJson = globalJson; - this.model = model; - this.mav = mav; - this.httpServletRequest = httpServletRequest; - } - - @Override - public void run() { - //¸ù¾Ýmodel¸øPropertyEvaluationModel¸³Öµ - PropertyEvaluationModel propertyEvaluationModel = createPropertyEvaluationModelFromHouseInfomationModel(model); - -// RestfulModelAndView propertyEvaluationMav = new RestfulModelAndView(); -// mav.setViewType("rest"); -// if (StringUtils.isBlank(propertyEvaluationModel.getCity()) || StringUtils.isBlank(propertyEvaluationModel.getAddress()) || propertyEvaluationModel.getSize() <= 0) { -// mav.setModel(BasicModel.buildBadRequestModel("²ÎÊý·Ç·¨:³ÇÊÐ,µØÖ·,Ãæ»ý(size)Ϊ±ØÌîÏî")); -// return mav; -// } - if (propertyEvaluationModel.getDistrict() != null) { - //ÇøÓò±àÂëת·¿¼ÛÍøÇøÓò - FangjiaOfficialAreaMap fangjiaOfficialAreaMap = fangjiaOfficialAreaService.convertOfficialCodeToFangjia(propertyEvaluationModel.getDistrict()); - if (fangjiaOfficialAreaMap != null) { - propertyEvaluationModel.setDistrict(fangjiaOfficialAreaMap.getFangjiaDistrict()); - } - } - - boolean villaFlag = DataUtil.isVilla(propertyEvaluationModel.getSize(), propertyEvaluationModel.getName(), propertyEvaluationModel.getHeight(), propertyEvaluationModel.getRoom()); - - District district = null; - Map params = new HashMap(); - params.put("city", propertyEvaluationModel.getCity()); - if (StringUtils.isNotBlank(propertyEvaluationModel.getDistrict())) { - params.put("suggestDistrict", propertyEvaluationModel.getDistrict()); - } - params.put("address", propertyEvaluationModel.getAddress()); - if (StringUtils.isNotBlank(propertyEvaluationModel.getName())) { - params.put("suggestName", propertyEvaluationModel.getName()); - } - params.put("category", "district"); - String result = addressMatchProxyService.parser(params); - if (result != null) { - JSONObject json = globalJson; - json = JSONObject.fromObject(result); - if (json.getInt("code") == 200) { - Map map = (Map) json.get("result"); - if ((Integer) map.get("precise") >= 0) { - String propertyType = (String) map.get("propertyType"); - if (villaFlag && StringUtils.isNotBlank(propertyType) && !propertyType.equals("±ðÊû")) { - district = districtService.findByNameAndAlias((String) map.get("city"), (String) map.get("district"), (String) map.get("name") + "±ðÊû", "district"); - } - if (null == district) { - district = districtService.findByNameAndAlias((String) map.get("city"), (String) map.get("district"), (String) map.get("name"), "district"); - } - - } - } - } - - if (district == null) { - mav.setModel(BasicModel.buildBadRequestModel("¸ÃµØÖ·²»Ö§³Ö¹À¼Û£¡")); -// return mav; - } - propertyEvaluationModel.setDistrict(district.getRegion()); - propertyEvaluationModel.setName(district.getName()); - try { - evaluateAction(propertyEvaluationModel, httpServletRequest, houseValueInformation, mav); - } catch (IllegalAccessException e) { - throw new RuntimeException(e); - } - } - } - - private class UpdateHouseCaseRunnable implements Runnable { - private HouseValueInformationDto houseValueInformation; - - private JSONObject globalJson; - - private HouseInfomationModel model; - private RestfulModelAndView mav; - - public UpdateHouseCaseRunnable(HouseValueInformationDto houseValueInformation, JSONObject globalJson, HouseInfomationModel model, RestfulModelAndView mav) { - this.houseValueInformation = houseValueInformation; - this.globalJson = globalJson; - this.model = model; - this.mav = mav; - } - - @Override - public void run() { - //·¿Ô´Ñù±¾ - - //¹¹ÔìsampleQuery¶ÔÏó - SampleQuery sampleQuery = new SampleQuery(); - sampleQuery.setCity(model.getCity()); - sampleQuery.setStrctureArea(model.getSize()); - sampleQuery.setAddress(model.getAddress()); - -// RestfulModelAndView houseCaseMav = new RestfulModelAndView(); - List querys = null; - try { - querys = convertSampileQueryToBean(sampleQuery); - } catch (Exception e) { - mav.setModel(BasicModel.buildBadRequestModel(e.getMessage())); - } - if (null == sampleQuery.getMax()) { - sampleQuery.setMax(10); - } - // ´Ë´¦Âý - long start = System.currentTimeMillis(); - List collaterals = czbankSampleService.findSample2(querys, sampleQuery.getMax()); - long end = System.currentTimeMillis(); - System.out.println("ÓÃʱ:" + (end - start)); - Collateral collateral = collaterals.get(0); - List samples = collateral.getSample(); - UniversalDto dto = UniversalDto.newDto(); - if (null != collateral.getMaxPrice()) { - dto.append("maxUnitPrice", collateral.getMaxPrice()); - } - if (null != collateral.getMinPrice()) { - dto.append("minUnitPrice", collateral.getMinPrice()); - } - dto.append("datas", samples); - houseValueInformation.setHouseCase(dto); - - } - } - - private class UpdateSurroundingPoiRunnable implements Runnable { - private HouseValueInformationDto houseValueInformation; - - private JSONObject globalJson; - - private HouseInfomationModel model; - private RestfulModelAndView mav; - - public UpdateSurroundingPoiRunnable(HouseValueInformationDto houseValueInformation, JSONObject globalJson, HouseInfomationModel model, RestfulModelAndView mav) { - this.houseValueInformation = houseValueInformation; - this.globalJson = globalJson; - this.model = model; - this.mav = mav; - } - - @Override - public void run() { - //ÖܱßPOI - -// RestfulModelAndView mav = new RestfulModelAndView(); -// mav.setViewType("rest"); - if (StringUtils.isBlank(model.getAddress())) { - mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "µØÖ·±ØÐëÊäÈë")); -// return mav; - } else { - String cat = "district"; - - HttpRequest request = new HttpRequest(); -// json = null; -// Map poiParams = new HashMap(); -// poiParams.put("city", model.getCity()); -// poiParams.put("address", model.getAddress()); -// poiParams.put("category", "property"); - //ÐÂÆ¥Åä½Ó¿Ú -// json = request.getJsonContent("http://192.168.0.100:32080/FangJiaNlpService/match", poiParams, "UTF-8"); - JSONObject json = globalJson; - District property = null; - if (json != null && json.size() > 0) { - MatchedBuildingDto matchedBuildingDto = CommonDtoUtils.transformV(MatchedBuildingDto.class, json); - property = districtService.findByNameAndAlias(matchedBuildingDto.getCity(), matchedBuildingDto.getDistrict(), matchedBuildingDto.getName(), cat); - if (null == property) { - mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "Ð¡ÇøÊý¾Ý²»´æÔÚ")); -// return mav; - } - DistrictFacilitys facilitys = districtFacilitysService.findByDistrict(property); -// mav.setModel(BasicModel.buildOKModel().setResult(facilitys)); - // ½«ÖܱßPOIÊý¾Ý·Åµ½½á¹û¼¯ - houseValueInformation.setSurroundingPoi(facilitys); - } else { - mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "Ð¡ÇøÊý¾Ý²»´æÔÚ")); - } - } -// return mav; -// houseValueInformation.setSurroundingPoi(mav); - - mav.setModel(BasicModel.buildOKModel().setResult(houseValueInformation)); -// return mav; - } - } - - private PropertyEvaluationModel createPropertyEvaluationModelFromHouseInfomationModel(HouseInfomationModel model) { - PropertyEvaluationModel propertyModel = new PropertyEvaluationModel(); - propertyModel.setCity(model.getCity()); - propertyModel.setAddress(model.getAddress()); - propertyModel.setSize(model.getSize()); - - if (StringUtils.isNotBlank(model.getDistrict())) { - propertyModel.setDistrict(model.getDistrict()); - } - if (StringUtils.isNotBlank(model.getName())) { - propertyModel.setName(model.getName()); - } - if (StringUtils.isNotBlank(model.getBuildingNumber())) { - propertyModel.setBuildingNumber(model.getBuildingNumber()); - } - if (StringUtils.isNotBlank(model.getUnitNumber())) { - propertyModel.setUnitNumber(model.getUnitNumber()); - } - if (model.getFloor() != null && model.getFloor() != 0) { - propertyModel.setFloor(model.getFloor()); - } - if (model.getMaxFloor() != null && model.getMaxFloor() != 0) { - propertyModel.setMaxFloor(model.getMaxFloor()); - } - if (model.getRoom() != null && model.getRoom() != 0) { - propertyModel.setRoom(model.getRoom()); - } - if (model.getHall() != 0) { - propertyModel.setHall(model.getHall()); - } - if (model.getToilet() != 0) { - propertyModel.setToilet(model.getToilet()); - } - if (model.getCalDate() != null) { - propertyModel.setCalDate(model.getCalDate()); - } - if (model.getPropertyType() != null) { - propertyModel.setPropertyType(model.getPropertyType()); - } - if (StringUtils.isNotBlank(model.getDirection())) { - propertyModel.setDirection(model.getDirection()); - } - if (StringUtils.isNotBlank(model.getDecoration())) { - propertyModel.setDecoration(model.getDecoration()); - } - - if (model.getDecorationCost() != null && model.getDecorationCost() != 0) { - propertyModel.setDecorationCost(model.getDecorationCost()); - } - - if (model.getDecorationAge() != 0) { - propertyModel.setDecorationAge(model.getDecorationAge()); - } - if (StringUtils.isNotBlank(model.getView())) { - propertyModel.setView(model.getView()); - } - if (StringUtils.isNotBlank(model.getNoise())) { - propertyModel.setNoise(model.getNoise()); - } - if (model.getGardenSize() != null && model.getGardenSize() != 0) { - propertyModel.setGardenSize(model.getGardenSize()); - } - if (model.getBasementSize() != null && model.getBasementSize() != 0) { - propertyModel.setBasementSize(model.getBasementSize()); - } - if (model.getOuterSize() != null && model.getOuterSize() != 0) { - propertyModel.setOuterSize(model.getOuterSize()); - } - if (model.getAtticSize() != null && model.getAtticSize() != 0) { - propertyModel.setAtticSize(model.getAtticSize()); - } - if (StringUtils.isNotBlank(model.getNegativeFactor())) { - propertyModel.setNegativeFactor(model.getNegativeFactor()); - } - if (model.getAge() != 0) { - propertyModel.setAge(model.getAge()); - } - if (model.getCarportPrice() != null && model.getCarportPrice() != 0) { - propertyModel.setCarportPrice(model.getCarportPrice()); - } - - if (StringUtils.isNotBlank(model.getFacilities())) { - propertyModel.setFacilities(model.getFacilities()); - } - if (StringUtils.isNotBlank(model.getInsidePosition())) { - propertyModel.setInsidePosition(model.getInsidePosition()); - } - return propertyModel; - } - - private List convertSampileQueryToBean(SampleQuery... queries) throws Exception { - - List queryBeans = new ArrayList(queries.length); - for (SampleQuery q : queries) { - - CollateralSampleQueryBean queryBean = new CollateralSampleQueryBean(); - BeanUtils.copyProperties(q, queryBean); -// String propertyTypeCode = queryBean.getPropertyTypeCode(); -// if(!Arrays.asList("01", "02", "03").contains(propertyTypeCode)){ -// throw new Exception("propertyTypeCodeȡֵ·Ç·¨"); -// } - String cat = "district"; - - if (StringUtils.isNotBlank(queryBean.getCity()) && StringUtils.isNotBlank(queryBean.getDistrict()) && StringUtils.isNotBlank(queryBean.getBuildingName())) { - District property = districtService.findByNameAndAlias(queryBean.getCity(), queryBean.getDistrict(), queryBean.getBuildingName(), cat); - if (property == null) { - throw new Exception("δÕÒµ½¸ÃÐ¡Çø"); - } - queryBean.setProperty(property); - } else if (StringUtils.isNotBlank(queryBean.getAddress())) { - HttpRequest request = new HttpRequest(); - JSONObject json = null; - String address = queryBean.getAddress().replace(" ", "").replace("%", ""); -// Map params = new HashMap(); -// params.put("city", queryBean.getCity()); -// params.put("address", address); -// params.put("category", "property"); - //ÐÂÆ¥Åä½Ó¿Ú -// json = request.getJsonContent("http://192.168.0.100:32080/FangJiaNlpService/match", params, "UTF-8"); - json = globalJson; - if (json != null && json.size() > 0) { - MatchedBuildingDto dto = CommonDtoUtils.transformV(MatchedBuildingDto.class, json); - District property = districtService.findByNameAndAlias(dto.getCity(), dto.getDistrict(), dto.getName(), cat); - if (property == null) { - throw new Exception("δÕÒµ½¸ÃÐ¡Çø"); - } - queryBean.setProperty(property); - } else { - throw new Exception("δÕÒµ½¸ÃÐ¡Çø"); - } - } - String estateType = queryBean.getProperty().getEstateType2(); - queryBean.setPropertyTypeCode("01"); - if (StringUtils.isNotBlank(estateType)) { - if (estateType.equals("ÆÕͨסլ")) { - queryBean.setPropertyTypeCode("01"); - } else if (estateType.equals("±ðÊû")) { - queryBean.setPropertyTypeCode("02"); - } else if (estateType.equals("ÉÌס")) { - queryBean.setPropertyTypeCode("03"); - } - } - - Integer decrCondCode = queryBean.getDecrCondCode(); - if (decrCondCode == null) { - decrCondCode = 2; - } - if (decrCondCode > 5 || decrCondCode < 1) { - throw new Exception("decrCondCodeȡֵ·Ç·¨"); - } - Integer towardDirectCode = queryBean.getTowardDirectCode(); - if (towardDirectCode == null) { - towardDirectCode = 3; - } - if (towardDirectCode > 10 || towardDirectCode < 1) { - throw new Exception("towardDirectCodeȡֵ·Ç·¨"); - } - queryBeans.add(queryBean); - } - return queryBeans; - } - - private void adjustPriceByRatio(District district, Evaluation evaluation) { - - try { - ApiUserCfg apiUserCfg_pt = apiUserCfgService.findByUserId(Long.valueOf(evaluation.getFromUserId()), ApiUserCfg.ApiUserCfgKey.PRICE_TYPE); - if (apiUserCfg_pt != null && apiUserCfg_pt.getCfgValue() != null) { - String priceType = apiUserCfg_pt.getCfgValue().toString(); - // ÆÀ¹À¼ÛÔòϵÊýµ÷Õû - if (StringUtils.isNotBlank(priceType) && "evaluate".equals(priceType)) { - EvaluateRatio evaluateRatio = null; - if (StringUtils.isNotBlank(district.getRegion())) { - evaluateRatio = evaluateRatioService.findByCityAndRegion(district.getCity(), district.getRegion()); - } - if (evaluateRatio == null) { - evaluateRatio = evaluateRatioService.findByCity(district.getCity()); - } - if (evaluateRatio != null) { - // ϵÊýÌí¼Ó - long totalPrice = evaluation.getBigTotalPrice(); - totalPrice = (long) (totalPrice * (1 + evaluateRatio.getRatio())); - evaluation.setBigTotalPrice(totalPrice); - evaluation.setAvgPrice((int) (totalPrice / evaluation.getArea())); - } - } - } - } catch (Exception ex) { - LOGGER.error("ϵÊýϵ÷Òì³£{}", ex.getMessage()); - } - } - - public Object evaluateAction(PropertyEvaluationModel model, HttpServletRequest request, HouseValueInformationDto houseValueInformation, RestfulModelAndView mav) - throws NumberFormatException, IllegalAccessException { -// RestfulModelAndView mav = new RestfulModelAndView(); -// mav.setViewType("rest"); - if (StringUtils.isBlank(model.getCity()) || StringUtils.isBlank(model.getName()) - || StringUtils.isBlank(model.getDistrict()) || model.getSize() <= 0) { - mav.setModel(BasicModel.buildBadRequestModel("²ÎÊý·Ç·¨:³ÇÊÐ,ÇøÓò,Ð¡ÇøÃû,Ãæ»ý(size)Ϊ±ØÌîÏî")); - return mav; - } - if (model.getCity().endsWith("ÊÐ")) { - model.setCity(model.getCity().replaceAll("ÊÐ$", "")); - } - if (StringUtils.isNotBlank(request.getParameter("calDate"))) { - Date calDate = null; - try { - calDate = DateUtils.parseDate(request.getParameter("calDate"), new String[]{"yyyy-MM-dd"}); - } catch (ParseException e) { - - } - if (calDate == null) { - mav.setModel(BasicModel.buildBadRequestModel("calDate:Êý¾ÝÀàÐͲ»ºÏ·¨")); - return mav; - } else { - model.setCalDate(calDate); - } - } -// Ïȵ½CPDB¿âÖвéÕÒÐ¡Çø - - District district = districtService.findByNameAndAlias(model.getCity(), model.getDistrict(), model.getName(), - "district"); - if (district == null) { - if (model.getDistrict().contains("ÊÐÏ½Çø") || model.getDistrict().contains(model.getCity())) { - district = districtService.findByNameAndAlias(model.getCity(), null, model.getName(), "district"); - } - if (district == null) { - mav.setModel(BasicModel.buildBadRequestModel("¸ÃÐ¡Çø²»´æÔÚ")); - return mav; - } - } - model.setName(district.getName()); - - if (model.getCarportPrice() != null && (model.getCarportPrice() < 0 || model.getCarportPrice() > 1000000)) { - mav.setModel(BasicModel.buildBadRequestModel("carportPrice(³µÎ»)ȡֵ²»ºÏ·¨")); - return mav; - } - if (model.getMaxFloor() != null && (model.getMaxFloor() <= 0 || model.getMaxFloor() > 59)) { - mav.setModel(BasicModel.buildBadRequestModel("maxFloorȡֵ·Ç·¨,ÕýÈ··¶Î§[1,60)")); - return mav; - } - - if (model.getFloor() != null && (model.getFloor() <= 0 || model.getFloor() > 59)) { - mav.setModel(BasicModel.buildBadRequestModel("floorȡֵ·Ç·¨,ÕýÈ··¶Î§[1,60)")); - return mav; - } - if (model.getMaxFloor() != null && model.getFloor() != null && model.getFloor() > model.getMaxFloor()) { - mav.setModel(BasicModel.buildBadRequestModel("ËùÔÚÂ¥²ã²»ÄÜ´óÓÚ×ÜÂ¥²ã")); - return mav; - } - - if (model.getFloor() == null) { - JSONObject structureOb = addressMatchProxyService.addressStructure(district.getCity(), model.getAddress()); - if (structureOb != null) { - if (structureOb.containsKey("buildingNumber")) { - model.setBuildingNumber(structureOb.getString("buildingNumber")); - } - - if (structureOb.containsKey("roomNumber")) { - String roomNumber = structureOb.getString("roomNumber"); - model.setFloor(getFloor(roomNumber)); - } - - } - } - - if (model.getMaxFloor() == null && model.getFloor() != null && StringUtils.isNotBlank(model.getBuildingNumber())) { - Loudong loudong = loudongService.findForEvaluate(district.getId(), model.getBuildingNumber(), model.getUnitNumber()); - if (loudong != null && loudong.getFloors() >= model.getFloor()) { - model.setMaxFloor(loudong.getFloors()); - } - } - model.setRegion(district.getRegion()); - model.setDistrictName(district.getName()); - if (StringUtils.isBlank(model.getPropertyType())) { - if (district.getEstateType2() != null && district.getEstateType2().contains("±ðÊû")) { - model.setPropertyType("1"); - } - } - - if (model.getCalDate() != null) { - if (new Date().before(model.getCalDate())) { - model.setCalDate(DateUtil.getFirstDayOfWeek(new Date())); - } else { - model.setCalDate(DateUtil.getFirstDayOfWeek(model.getCalDate())); - } - } else { - model.setCalDate(DateUtil.getFirstDayOfWeek(new Date())); - } - - - Evaluation evaluation = evaluationService.evaluate(district, buildEvaluation(model, request), - model.getCalDate()); - Double cityPriceCredit = null; - if (StringUtils.isNotBlank(evaluation.getFromUserId())) { - try { - ApiUserAuthority apiUserAuthority = apiUserAuthorityService - .findByUserId(Long.valueOf(evaluation.getFromUserId())); - if (apiUserAuthority.getCityCreditMap() != null - && apiUserAuthority.getCityCreditMap().containsKey(evaluation.getCity())) { - cityPriceCredit = apiUserAuthority.getCityCreditMap().get(evaluation.getCity()); - if (cityPriceCredit > 1 || cityPriceCredit < 0) { - cityPriceCredit = null; - } - } - } catch (IllegalAccessException e) { - e.printStackTrace(); - } - - this.adjustPriceByRatio(district, evaluation); - } - - // µ÷ÕûÃæ»ý²»Í¬Ãæ»ý¼Û¸ñ - try { - DistrictStatBo districtStatBo = districtStatService.findDistrictStat(new DistrictKey(district)); - int orgAvgPrice = 0; - if (districtStatBo != null) { - if (StringUtils.isNotBlank(district.getEstateType2()) && district.getEstateType2().contains("±ðÊû") && districtStatBo.getVillaDistrictStat() != null) { - orgAvgPrice = districtStatBo.getVillaDistrictStat().getAvgPrice(); - } else if (districtStatBo.getDistrictStat() != null) { - orgAvgPrice = districtStatBo.getDistrictStat().getAvgPrice(); - } - } - if (evaluation != null && evaluation.getAvgPrice() != null && evaluation.getAvgPrice() > 0) { - int factorPrice = evaluation.getAvgPrice(); - int avgPrice = evaluateFactorService.recompose(district.getCity(), district.getRegion(), evaluation.getArea(), factorPrice, orgAvgPrice); - Integer minPrice = (int) (evaluation.getAvgPrice() * 0.95); - Integer maxPrice = (int) (evaluation.getAvgPrice() * 1.05); - // Æ«Àë¶È³¬¹ý5%²»½øÐе÷Õû - if (minPrice <= avgPrice && avgPrice <= maxPrice) { - evaluation.setAvgPrice(avgPrice); - evaluation.setBigTotalPrice((long) (avgPrice * evaluation.getArea())); - } - } - } catch (Exception ex) { - LOGGER.error("µ÷ÕûÃæ»ý²»Í¬Ãæ»ý¼Û¸ñÒì³£{}", ex.getMessage()); - } - - if (evaluation.getTotalPrice() != null && evaluation.getTotalPrice() != 0 - && (cityPriceCredit == null || evaluation.getCredit() >= cityPriceCredit)) { - Map districtPriceMap = new HashMap(); - districtPriceMap.put("city", district.getCity()); - districtPriceMap.put("district", district.getRegion()); - districtPriceMap.put("name", district.getName()); - districtPriceMap.put("totalPrice", evaluation.getBigTotalPrice()); - districtPriceMap.put("avgPrice", evaluation.getAvgPrice()); - - // ¸ù¾Ý³ÇÊÐµÈ ¼¶ÉèÖÃD¼¶¿ÉÐÅ¶È - ApiUserAuthority apiUserAuthority = apiUserAuthorityService - .findByUserId(Long.valueOf(evaluation.getFromUserId())); - if (apiUserAuthority != null && null != apiUserAuthority.getCreditLevelStatus() - && apiUserAuthority.getCreditLevelStatus() == 1) { - double dCredit = 0.61; - if (null != apiUserAuthority.getPriceRatingMap()) { - ServerArea serverArea = serverAreaService.findByDisplay(evaluation.getCity()); - Map rateMap = apiUserAuthority.getPriceRatingMap(); - if (null != rateMap) { - dCredit = rateMap.get(CITYLEVEL_MAP.get(serverArea.getNewCityGrade().toString())); - } - } - Map rMap = getLastEvaluationPrice(district, evaluation, dCredit); - - if (model.getScope() == EVALUATE_SHOW_DETAIL) { - if (null != rMap) { - if (rMap.containsKey("level")) { - districtPriceMap.put("level", rMap.get("level")); - } - if (rMap.containsKey("other_price")) { - districtPriceMap.put("other_price", rMap.get("other_price")); - } - } - } - - Long lastPrice = (Long) rMap.get("lastPrice"); - - if (null != lastPrice) { - districtPriceMap.put("totalPrice", lastPrice); - if (lastPrice > 0 && lastPrice != evaluation.getBigTotalPrice()) { - districtPriceMap.put("avgPrice", (int) (lastPrice / evaluation.getArea())); - } - } else { - mav.setModel(BasicModel.buildOKModel().setMsg("ÔÝʱ²»Ö§³Ö¸ÃÐ¡ÇøµÄ¹À¼Û").markNoData()); - return mav; - } - - } else { - districtPriceMap.put("totalPrice", evaluation.getBigTotalPrice()); - } - - if (model.getScope() == EVALUATE_SHOW_DETAIL) { - districtPriceMap.put("evaluateWay", evaluation.getEvaluateWay()); - districtPriceMap.put("credit", evaluation.getCredit()); - districtPriceMap.put("id", evaluation.getId()); - } - // ½«ÆÀ¹À¼Û·Åµ½½á¹û¼¯ - houseValueInformation.setAddressValue(districtPriceMap); -// mav.setModel(BasicModel.buildOKModel().setResult(districtPriceMap)); - try { - if (StringUtils.isNotBlank(evaluation.getFromUserId()) && !evaluation.getFromUserId().equals("1007497")) { - openApiLogService.saveLog(CommonUtils.convertToMap(model), districtPriceMap, evaluation, "/property/evaluate"); - } - - } catch (Exception e) { - e.printStackTrace(); - } - - return mav; - } else { - evaluationService.remove(evaluation.getId()); - mav.setModel(BasicModel.buildOKModel().setMsg("ÔÝʱ²»Ö§³Ö¸ÃÐ¡ÇøµÄ¹À¼Û").markNoData()); - return mav; - } - } - - private Integer getFloor(String roomNumber) { - if (StringUtils.isNotBlank(roomNumber) && DataUtil.isNumber(roomNumber)) { - if (roomNumber.length() == 3) { - return Integer.valueOf(roomNumber.substring(0, 1)); - } else if (roomNumber.length() == 4) { - return Integer.valueOf(roomNumber.substring(0, 2)); - } else { - return null; - } - } - return null; - } - - private Evaluation buildEvaluation(PropertyEvaluationModel model, HttpServletRequest request) { - Evaluation evaluation = new Evaluation(); - evaluation.setCity(model.getCity()); - evaluation.setRegion(model.getRegion()); - evaluation.setDistrictName(model.getName()); - evaluation.setDirection(DIRECTION.get(model.getDirection())); - evaluation.setFitment(EVALUATION_MODEL_FITMENT.get(FITMENT.get(StringUtils.isNotBlank(model.getDecoration()) ? - model.getDecoration() : model.getFitment()))); - evaluation.setNoise(NOISE.get(model.getNoise())); - evaluation.setEstateType(PROPERTY_TYPES.get(model.getPropertyType())); - evaluation.setSight(SIGHT.get(model.getView())); - evaluation.setAtticArea(model.getAtticSize()); - evaluation.setTerraceArea(model.getOuterSize()); - evaluation.setBasementArea(model.getBasementSize()); - evaluation.setGardenArea(model.getGardenSize()); - String worryFacility = model.getNegativeFactor(); - evaluation.setWorryFacility(NEGATIVE_FACTOR.get(worryFacility)); - evaluation.setCreationDate(new Date()); - evaluation.setModificationDate(new Date()); - evaluation.setClientNo(model.getClientNo()); - if (0 != model.getAge()) { - evaluation.setAge(model.getAge()); - } - evaluation.setArea(model.getSize()); - if (ArrayUtils.isNotEmpty(model.getBuildQuality())) { - evaluation.setBuildQuality(convertToString(model.getBuildQuality())); - } - if (StringUtils.isNotBlank(model.getBuildType())) { - evaluation.setBuildType(model.getBuildType()); - } - if (StringUtils.isNotBlank(model.getCarport())) { - evaluation.setCarport(model.getCarport()); - } - if (model.getDecorationAge() >= 1 && model.getDecorationAge() <= 5) { - evaluation.setFitmentAge(model.getDecorationAge()); - } - evaluation.setCarportPrice(model.getCarportPrice()); - evaluation.setCity(model.getCity()); - evaluation.setDistrictName(model.getName()); - if (model.getDecorationCost() != null && model.getDecorationCost() > 0) { - evaluation.setFitmentCharge(model.getDecorationCost()); - } - if (0 != model.getHall()) { - evaluation.setHall(model.getHall()); - } - if (null != model.getFloor()) { - evaluation.setFloor(model.getFloor()); - } - if (model.getMaxFloor() != null && 0 != model.getMaxFloor()) { - evaluation.setHeight(model.getMaxFloor()); - } - if (StringUtils.isNotBlank(model.getBuildingNumber())) { - evaluation.setHouseNum(model.getBuildingNumber()); - } - if (StringUtils.isNotBlank(model.getHouseProperty())) { - evaluation.setHouseProperty(model.getHouseProperty()); - } - if (StringUtils.isNotBlank(model.getInsidepos())) { - evaluation.setInsidepos(model.getInsidepos()); - } - if (StringUtils.isNotBlank(model.getLightingVentilation())) { - evaluation.setLightingVentilation(model.getLightingVentilation()); - } - - if (StringUtils.isNotBlank(model.getOtherFactor())) { - evaluation.setOtherFactor(model.getOtherFactor()); - } - evaluation.setRegion(model.getDistrict()); - if (null != model.getRoom()) { - evaluation.setRoom(model.getRoom()); - } - if (StringUtils.isNotBlank(model.getRoomNumber())) { - evaluation.setRoomNum(model.getRoomNumber()); - } - if (StringUtils.isNotBlank(model.getSideset())) { - evaluation.setSideset(model.getSideset()); - } - if (0 != model.getToilet()) { - evaluation.setToilet(model.getToilet()); - } - if (model.getFacilities() != null) { - String facilities = model.getFacilities(); - String[] fs = facilities.split(","); - for (int i = 0; i < fs.length; i++) { - fs[i] = FACILITIES.get(fs[i]); - } - evaluation.setFacilities(convertToString(fs)); - } - - if (StringUtils.isNotBlank(model.getFacade())) { - evaluation.setFacade(model.getFacade()); - } - if (StringUtils.isNotBlank(model.getTraffice())) { - evaluation.setTraffice(model.getTraffice()); - } - if (StringUtils.isNotBlank(model.getShape())) { - evaluation.setShape(model.getShape()); - } - if (StringUtils.isNotBlank(model.getObstacle())) { - evaluation.setObstacle(model.getObstacle()); - } - if (StringUtils.isNotBlank(model.getIndustry())) { - evaluation.setIndustry(model.getIndustry()); - } - if (StringUtils.isNotBlank(model.getSupportDevice())) { - evaluation.setSupportDevice(model.getSupportDevice()); - } - if (StringUtils.isNotBlank(model.getLeftPosition())) { - evaluation.setLeftPosition(model.getLeftPosition()); - } - if (StringUtils.isNotBlank(model.getShopType())) { - evaluation.setShopType(model.getShopType()); - } - if (StringUtils.isNotBlank(model.getShopUnique())) { - evaluation.setShopUnique(model.getShopUnique()); - } - if (StringUtils.isNotBlank(model.getLocation())) { - evaluation.setLocation(model.getLocation()); - } - if (model.isNewDistrict()) { - evaluation.setNewDistrict(model.isNewDistrict()); - } - String ip = AnalyticsUtil.getIpAddress(ActionContext.getContext().getRequest()); - evaluation.setIp(ip); - AuthenticationBean authenticationBean = (AuthenticationBean) request - .getAttribute(AuthenticationBean.ATTR_AUTHENTICATION_BEAN); - if (authenticationBean != null && authenticationBean.apiUser != null) { - evaluation.setFromUserId(String.valueOf(authenticationBean.apiUser.getId())); - } - evaluation.setSource("api_property_evaluation"); - return evaluation; - } - - private Map getLastEvaluationPrice(District district, Evaluation evaluation, double dCredit) - throws NumberFormatException, IllegalAccessException { - Date startDate = DateUtil.parseDate(DateUtil.addMonth(new Date(), -6), "yyyy-MM-dd"); - // µÚÈý·½¼Û¸ñ - Map otherPriceRets = averageStatisticsService.findFirstAverageStatictics(district.getCity(), - district.getRegion(), district.getName(), district.getCategory(), startDate); - if (null == otherPriceRets) { - otherPriceRets = new HashMap(); - } - - otherPriceRets.put("fjw_price", evaluation.getAvgPrice()); - Map levelMap = getPriceLevel(otherPriceRets, evaluation.getCredit()); - Long lastPrice = getLastPrice(levelMap, otherPriceRets, evaluation, dCredit); - - Map rMap = new HashMap(); - rMap.put("lastPrice", lastPrice); - if (null != levelMap && levelMap.containsKey("level")) { - String priceLevel = (String) levelMap.get("level"); - rMap.put("level", priceLevel); - } - rMap.put("other_price", otherPriceRets); - return rMap; - } - - private Map getPriceLevel(Map otherPriceRets, double credit) { - - Integer avgPrice = (Integer) otherPriceRets.get("fjw_price"); - - int keyCount = 0; - int commonCount = 0; - int isExistCount = 0; - - List prices = new ArrayList(); - List smallPrices = new ArrayList(); - - if (null != otherPriceRets.get("fanggugu_price")) { - Integer fangguguPrice = (Integer) otherPriceRets.get("fanggugu_price"); - int mod = avgPrice - fangguguPrice; - double temp = DataUtil.getDoubleRound(2, mod * 100 / avgPrice); - temp = Math.abs(temp); - if (temp <= 15) { - keyCount++; - } else { - prices.add(fangguguPrice); - } - isExistCount++; - } - if (null != otherPriceRets.get("yungujia_price")) { - Integer yungujiaPrice = (Integer) otherPriceRets.get("yungujia_price"); - int mod = avgPrice - yungujiaPrice; - double temp = DataUtil.getDoubleRound(2, mod * 100 / avgPrice); - temp = Math.abs(temp); - if (temp <= 15) { - keyCount++; - } else { - prices.add(yungujiaPrice); - } - - isExistCount++; - } - - if (null != otherPriceRets.get("zhugezhaofang_price")) { - Integer zhugezhaofangPrice = (Integer) otherPriceRets.get("zhugezhaofang_price"); - int mod = avgPrice - zhugezhaofangPrice; - double temp = DataUtil.getDoubleRound(2, mod * 100 / avgPrice); - temp = Math.abs(temp); - if (temp <= 15) { - keyCount++; - } else { - prices.add(zhugezhaofangPrice); - } - - isExistCount++; - } - - if (null != otherPriceRets.get("lianjia_price")) { - Integer lianjiaPrice = (Integer) otherPriceRets.get("lianjia_price"); - int mod = avgPrice - lianjiaPrice; - double temp = DataUtil.getDoubleRound(2, mod * 100 / avgPrice); - temp = Math.abs(temp); - if (temp <= 15) { - keyCount++; - } else { - prices.add(lianjiaPrice); - } - isExistCount++; - } - if (null != otherPriceRets.get("anjuke_price")) { - Integer anjukePrice = (Integer) otherPriceRets.get("anjuke_price"); - int mod = avgPrice - anjukePrice; - double temp = DataUtil.getDoubleRound(2, mod * 100 / avgPrice); - temp = Math.abs(temp); - if (temp <= 15) { - commonCount++; - smallPrices.add(anjukePrice); - } else { - prices.add(anjukePrice); - } - - isExistCount++; - } - if (null != otherPriceRets.get("ganji_price")) { - Integer ganjiPrice = (Integer) otherPriceRets.get("ganji_price"); - int mod = avgPrice - ganjiPrice; - double temp = DataUtil.getDoubleRound(2, mod * 100 / avgPrice); - temp = Math.abs(temp); - if (temp <= 15) { - commonCount++; - smallPrices.add(ganjiPrice); - } else { - prices.add(ganjiPrice); - } - - isExistCount++; - } - if (null != otherPriceRets.get("soufan_price")) { - Integer soufan_price = (Integer) otherPriceRets.get("soufan_price"); - int mod = avgPrice - soufan_price; - double temp = DataUtil.getDoubleRound(2, mod * 100 / avgPrice); - temp = Math.abs(temp); - if (temp <= 15) { - commonCount++; - smallPrices.add(soufan_price); - } else { - prices.add(soufan_price); - } - - isExistCount++; - } - if (null != otherPriceRets.get("tobushi_price")) { - Integer tobushi = (Integer) otherPriceRets.get("tobushi_price"); - int mod = avgPrice - tobushi; - double temp = DataUtil.getDoubleRound(2, mod * 100 / avgPrice); - temp = Math.abs(temp); - if (temp <= 15) { - commonCount++; - smallPrices.add(tobushi); - } else { - prices.add(tobushi); - } - - isExistCount++; - } - - if (null != otherPriceRets.get("zhongyuan_price")) { - Integer zhongyuanPrice = (Integer) otherPriceRets.get("zhongyuan_price"); - int mod = avgPrice - zhongyuanPrice; - double temp = DataUtil.getDoubleRound(2, mod * 100 / avgPrice); - temp = Math.abs(temp); - if (temp <= 15) { - commonCount++; - smallPrices.add(zhongyuanPrice); - } else { - prices.add(zhongyuanPrice); - } - - isExistCount++; - } - - Map retMap = new HashMap(); - String level = null; - if (keyCount >= 2) { - level = "A"; - } else if (keyCount >= 1 && commonCount >= 1) { - level = "A"; - } else if (keyCount >= 1 || commonCount >= 2) { - level = "B"; - } else if (commonCount >= 1) { - level = "C"; - } else if (isExistCount == 0) { - level = "D"; - } else if (isExistCount >= 1) { - if (isExistCount == 1) { - level = "D"; - } else { - level = "E"; - } - } - - if (credit == 0) { - level = "E"; - } - - if (StringUtils.isNotBlank(level)) { - retMap.put("level", level); - retMap.put("prices", prices); - retMap.put("small_prices", smallPrices); - } - return retMap; - } - - private Long getLastPrice(Map retMap, Map otherPriceRets, Evaluation evaluation, double dCredit) { - Long lastPrice = null; - if (null != retMap) { - String priceLevel = (String) retMap.get("level"); - - if (priceLevel.equals("D")) { - - lastPrice = inputResultByWebsite(otherPriceRets, evaluation, dCredit); - - } else if (priceLevel.equals("E")) { - if (evaluation.getCredit() >= 0.65) { - lastPrice = evaluation.getBigTotalPrice(); - } else { - List prices = (List) retMap.get("prices"); - int avgPrice = 0; - if (prices != null) { - avgPrice = findNewPrice(prices, evaluation.getAvgPrice()); - } - // ÔÚ dCreditÓë0.65Ö®¼ä - if (evaluation.getCredit() >= dCredit && dCredit < 0.65) { - if (avgPrice > 0) { - Double newTotalPrice = avgPrice * evaluation.getArea(); - lastPrice = newTotalPrice.longValue(); - } else { - if (null != otherPriceRets.get("lianjia_price")) { - Integer lianjiaPrice = (Integer) otherPriceRets.get("lianjia_price"); - Double newTotalPrice = lianjiaPrice * evaluation.getArea(); - lastPrice = newTotalPrice.longValue(); - } else if (null != otherPriceRets.get("zhugezhaofang_price")) { - Integer zhugezhaofangPrice = (Integer) otherPriceRets.get("zhugezhaofang_price"); - Double newTotalPrice = zhugezhaofangPrice * evaluation.getArea(); - lastPrice = newTotalPrice.longValue(); - } else if (null != otherPriceRets.get("yungujia_price")) { - Integer yungujiaPrice = (Integer) otherPriceRets.get("yungujia_price"); - Double newTotalPrice = yungujiaPrice * evaluation.getArea(); - lastPrice = newTotalPrice.longValue(); - } else if (null != otherPriceRets.get("fanggugu_price")) { - Integer fangguguPrice = (Integer) otherPriceRets.get("fanggugu_price"); - Double newTotalPrice = fangguguPrice * evaluation.getArea(); - lastPrice = newTotalPrice.longValue(); - } else { - lastPrice = evaluation.getBigTotalPrice(); - } - } - } else if (evaluation.getCredit() < dCredit) {// ÔÚdCreditÒÔÏ - if (avgPrice > 0) { - Double newTotalPrice = avgPrice * evaluation.getArea(); - lastPrice = newTotalPrice.longValue(); - } else { - if (null != otherPriceRets.get("lianjia_price")) { - Integer lianjiaPrice = (Integer) otherPriceRets.get("lianjia_price"); - Double newTotalPrice = lianjiaPrice * evaluation.getArea(); - lastPrice = newTotalPrice.longValue(); - } else if (null != otherPriceRets.get("zhugezhaofang_price")) { - Integer zhugezhaofangPrice = (Integer) otherPriceRets.get("zhugezhaofang_price"); - Double newTotalPrice = zhugezhaofangPrice * evaluation.getArea(); - lastPrice = newTotalPrice.longValue(); - } else if (null != otherPriceRets.get("yungujia_price")) { - Integer yungujiaPrice = (Integer) otherPriceRets.get("yungujia_price"); - Double newTotalPrice = yungujiaPrice * evaluation.getArea(); - lastPrice = newTotalPrice.longValue(); - } else if (null != otherPriceRets.get("fanggugu_price")) { - Integer fangguguPrice = (Integer) otherPriceRets.get("fanggugu_price"); - Double newTotalPrice = fangguguPrice * evaluation.getArea(); - lastPrice = newTotalPrice.longValue(); - } - } - } - } - - } else if (priceLevel.equals("C")) { - List smallPrices = (List) retMap.get("small_prices"); - if (smallPrices != null) { - smallPrices.add(evaluation.getAvgPrice()); - int avgPrice = sum(smallPrices) / smallPrices.size(); - Double newTotalPrice = avgPrice * evaluation.getArea(); - lastPrice = newTotalPrice.longValue(); - } - } else { - lastPrice = evaluation.getBigTotalPrice(); - } - } - return lastPrice; - } - - private Integer sum(List smallPrices) { - int sum = 0; - for (int price : smallPrices) { - sum += price; - } - return sum; - } - - private Long inputResultByWebsite(Map otherPriceRets, Evaluation evaluation, double dCredit) { - Long lastPrice = null; - if (evaluation.getCredit() >= dCredit) { - lastPrice = evaluation.getBigTotalPrice(); - } else { - if (evaluation.getCredit() < dCredit) { - if (null != otherPriceRets.get("lianjia_price")) { - Integer lianjiaPrice = (Integer) otherPriceRets.get("lianjia_price"); - Double newTotalPrice = lianjiaPrice * evaluation.getArea(); - lastPrice = newTotalPrice.longValue(); - } else if (null != otherPriceRets.get("zhugezhaofang_price")) { - Integer zhugezhaofangPrice = (Integer) otherPriceRets.get("zhugezhaofang_price"); - Double newTotalPrice = zhugezhaofangPrice * evaluation.getArea(); - lastPrice = newTotalPrice.longValue(); - } else if (null != otherPriceRets.get("yungujia_price")) { - Integer yungujiaPrice = (Integer) otherPriceRets.get("yungujia_price"); - Double newTotalPrice = yungujiaPrice * evaluation.getArea(); - lastPrice = newTotalPrice.longValue(); - } else if (null != otherPriceRets.get("fanggugu_price")) { - Integer fangguguPrice = (Integer) otherPriceRets.get("fanggugu_price"); - Double newTotalPrice = fangguguPrice * evaluation.getArea(); - lastPrice = newTotalPrice.longValue(); - } else { - lastPrice = evaluation.getBigTotalPrice(); - } - } else { - lastPrice = evaluation.getBigTotalPrice(); - } - } - return lastPrice; - } - - private Integer findNewPrice(List prices, int avgPrice) { - int minValue1 = Integer.MAX_VALUE; - List> values = new ArrayList>(); - int fjw_price = avgPrice; - - // ÕÒ³ö×îС²î - for (int i = 0; i < prices.size() - 1; i++) { - int a = prices.get(i); - for (int j = i + 1; j < prices.size(); j++) { - int b = prices.get(j); - int mod = Math.abs(a - b); - if (mod < minValue1) { - minValue1 = mod; - } - } - } - - // ¸ù¾Ý×îС²îÕÒ³ö½á¹û - for (int i = 0; i < prices.size() - 1; i++) { - int a = prices.get(i); - for (int j = i + 1; j < prices.size(); j++) { - int b = prices.get(j); - int mod = Math.abs(a - b); - if (mod == minValue1) { - values.add(Arrays.asList(a, b)); - } - } - } - - int minValue2 = Integer.MAX_VALUE; - int lastValue = 0; - if (values.size() >= 1) { - for (List value : values) { - int newPrice = (value.get(0) + value.get(1)) / 2; - int mod = Math.abs(fjw_price - newPrice); - if (mod < minValue2) { - minValue2 = mod; - lastValue = newPrice; - } - } - } - - if (lastValue > 0) { - double temp = DataUtil.getDoubleRound(2, minValue1 * 100 / lastValue); - temp = Math.abs(temp); - if (temp > 15) { - lastValue = 0; - } - } - return lastValue; - } - - - public void setEvaluationService(EvaluationService evaluationService) { - this.evaluationService = evaluationService; - } - - public void setDistrictService(DistrictService districtService) { - this.districtService = districtService; - } - - public void setAddressService(AddressService addressService) { - } - - public void setDistrictStatService(DistrictStatService districtStatService) { - this.districtStatService = districtStatService; - } - - protected AddressMatchLogService addressMatchLogService; - - public void setAddressMatchLogService(AddressMatchLogService addressMatchLogService) { - this.addressMatchLogService = addressMatchLogService; - } - - - public BatchEvaluateService getBatchEvaluateService() { - return batchEvaluateService; - } - - public void setBatchEvaluateService(BatchEvaluateService batchEvaluateService) { - this.batchEvaluateService = batchEvaluateService; - } - - public void setAddressMatchProxyService(AddressMatchProxyService addressMatchProxyService) { - this.addressMatchProxyService = addressMatchProxyService; - } - - public void setLoudongService(LoudongService loudongService) { - this.loudongService = loudongService; - } - - public void setApiUserAuthorityService(ApiUserAuthorityService apiUserAuthorityService) { - this.apiUserAuthorityService = apiUserAuthorityService; - } - - public void setAverageStatisticsService(AverageStatisticsService averageStatisticsService) { - this.averageStatisticsService = averageStatisticsService; - } - - public void setServerAreaService(ServerAreaService serverAreaService) { - this.serverAreaService = serverAreaService; - } - - public void setApiUserCfgService(ApiUserCfgService apiUserCfgService) { - this.apiUserCfgService = apiUserCfgService; - } - - public void setOpenApiLogService(OpenApiLogService openApiLogService) { - this.openApiLogService = openApiLogService; - } - - public void setFangjiaOfficialAreaService(FangjiaOfficialAreaService fangjiaOfficialAreaService) { - this.fangjiaOfficialAreaService = fangjiaOfficialAreaService; - } - - - public void setEvaluateRatioService(EvaluateRatioService evaluateRatioService) { - this.evaluateRatioService = evaluateRatioService; - } - - - public void setEvaluateFactorService(EvaluateFactorService evaluateFactorService) { - this.evaluateFactorService = evaluateFactorService; - } - - public void setCzbankSampleService(CzbankSampleService czbankSampleService) { - this.czbankSampleService = czbankSampleService; - } - - public void setDistrictFacilitysService(DistrictFacilitysService districtFacilitysService) { - this.districtFacilitysService = districtFacilitysService; + return result == null ? "192.168.20.6" : result; } } - -*/ diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/UsersController.java b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/UsersController.java index 951c354b3..dff7d888b 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/UsersController.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/UsersController.java @@ -4,22 +4,29 @@ import java.util.*; import com.fangjia.core.util.AnalyticsUtil; import com.fangjia.core.util.BeanUtils; +import com.fangjia.core.util.DataUtil; import com.fangjia.core.util.DateUtil; import com.fangjia.dal.QueryParam; +import com.fangjia.dal.mongo.model.ApiInvokeStatistical; import com.fangjia.dal.mongo.model.SendSmsLog; import com.fangjia.dal.mongo.open.model.ApiUserAuthority; import com.fangjia.dal.mongo.open.model.OpenResource; +import com.fangjia.dal.mongo.tool.model.ApiVisitCount; import com.fangjia.dal.mongo.tool.model.OpenUriAnaly; +import com.fangjia.dal.sql.model.ApiUser; import com.fangjia.open.HttpStatusCodeEnum; import com.fangjia.open.interceptors.AuthenticationBean; import com.fangjia.open.model.*; import com.fangjia.open.model.weixin.SendCodeJsonModel; import com.fangjia.open.model.weixin.SendCodeModel; +import com.fangjia.service.mongo.bkoff.ApiInvokeStatisticalService; import com.fangjia.service.open.*; +import com.fangjia.service.sql.ApiUserService; import net.sf.json.JSONObject; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.lang.StringUtils; +import org.json.JSONArray; import org.sothis.web.mvc.ActionContext; import org.sothis.web.mvc.ActionInvocation; import org.sothis.web.mvc.annotation.Param; @@ -41,6 +48,8 @@ public class UsersController { private ApiUserAuthorityService apiUserAuthorityService; private OpenResourceService openResourceService; private OpenUriAnalyService openUriAnalyService; + private ApiUserService apiUserService; + private ApiInvokeStatisticalService apiInvokeStatisticalService; /** @@ -125,58 +134,305 @@ public class UsersController { return json.toString(); } - public Object surplusCallCountAction() throws IllegalAccessException { + public Object surplusCallCountAction(ApiUserModel model) throws IllegalAccessException { RestfulModelAndView mav = new RestfulModelAndView(); ActionContext context = ActionContext.getContext(); HttpServletRequest request = context.getRequest(); AuthenticationBean instance = (AuthenticationBean) request.getAttribute(AuthenticationBean.ATTR_AUTHENTICATION_BEAN); + User user = null; + if (model.getUserId() != null && model.getUserId() > 0) { + user = userService.findById(model.getUserId()); + } if (null != instance) { - User user = instance.user; - List openResourceList = openResourceService.findAll(); - List list = new ArrayList(); - long id = user.getId(); - ApiUserAuthority authority = apiUserAuthorityService.findByUserId(id); - if (null != authority) { - // Óû§ÓеÄuri - List userResources = new ArrayList(); - for (OpenResource openResource : openResourceList) { - if (authority.getOpenResourseUris().contains(openResource.getUri())) { - userResources.add(openResource); - } + user = instance.user; + } + if (null == instance && user == null) { + mav.setModel(new BasicModel(HttpStatusCodeEnum.BAD_REQUEST_ERROR_KEY)); + return mav; + } + List openResourceList = openResourceService.findAll(); + List list = new ArrayList(); + long id = user.getId(); + ApiUserAuthority authority = apiUserAuthorityService.findByUserId(id); + if (null != authority) { + // Óû§ÓеÄuri + List userResources = new ArrayList(); + for (OpenResource openResource : openResourceList) { + if (authority.getOpenResourseUris().contains(openResource.getUri())) { + userResources.add(openResource); } - Map countMap = authority.getTotalCountMap(); - if (null != countMap) { - // ¸Ä³É±éÀúÓû§ÓеÄuri - for (OpenResource openResource : userResources) { - String uri = openResource.getUri(); - ApiMonitorInfo info = new ApiMonitorInfo(); - info.setApiUri(uri); - info.setApiName(openResource.getName()); - info.setUserId((int) id); - info.setUsername(user.getUserName()); - if (null != countMap.get(uri) && countMap.get(uri) > 0) { - long curVistedCount = apiVisitCountService.findApiVisitCountByDay(id, uri, DateUtil.truncateDay(new Date())); - long historyCount = apiVisitCountService.findApiVisitAllCount(id, uri, DateUtil.truncateDay(new Date())); - Integer totalCount = countMap.get(uri); - info.setTotalCallCount(Long.valueOf(totalCount)); - long usedCount = curVistedCount + historyCount; - info.setSurplusCallCount(totalCount - usedCount); - info.setUsedCallCount(usedCount); - } - list.add(info); + } + Map countMap = authority.getTotalCountMap(); + if (null != countMap) { + // ¸Ä³É±éÀúÓû§ÓеÄuri + for (OpenResource openResource : userResources) { + String uri = openResource.getUri(); + ApiMonitorInfo info = new ApiMonitorInfo(); + info.setApiUri(uri); + info.setApiName(openResource.getName()); + info.setUserId((int) id); + info.setUsername(user.getUserName()); + if (null != countMap.get(uri) && countMap.get(uri) > 0) { + long curVistedCount = apiVisitCountService.findApiVisitCountByDay(id, uri, DateUtil.truncateDay(new Date())); + long historyCount = apiVisitCountService.findApiVisitAllCount(id, uri, DateUtil.truncateDay(new Date())); + Integer totalCount = countMap.get(uri); + info.setTotalCallCount(Long.valueOf(totalCount)); + long usedCount = curVistedCount + historyCount; + info.setSurplusCallCount(totalCount - usedCount); + info.setUsedCallCount(usedCount); + } + list.add(info); + } + } + } + BasicModel basicModel = new BasicModel(200, "ok"); + basicModel.setResult(list); + mav.setModel(basicModel); + return mav; + } + + public Object callDetailAction(ApiUserModel model) throws IllegalAccessException { + RestfulModelAndView mav = new RestfulModelAndView(); + Date startDate = null; + Date endDate = null; + if (StringUtils.isNotBlank(model.getBegDateStr())) { + startDate = DateUtil.parseStringToDate(model.getBegDateStr()); + } + if (StringUtils.isNotBlank(model.getEndDateStr())) { + endDate = DateUtil.parseStringToDate(model.getEndDateStr()); + } + List analys = openUriAnalyService.findOpenUriAnalyLogs(model.getUserId(), model.getUri(), startDate, endDate); + List bos = null; + model.setQuery("uri"); + + Long userId = model.getUserId(); + ApiUserAuthority authority = apiUserAuthorityService.findByUserId(userId); + Map countMap = authority.getTotalCountMap(); + ApiUser apiUser = apiUserService.findApiUserById(userId); + User user = userService.findById(userId); + if (user != null) { + model.setUserName(user.getDisplayName()); + } + + if (model.getQuery().equals("uri")) { + bos = createAnalyBosByLink(analys); + model.setChartSeries(toChartString(bos)); + } + + long date = DateUtil.parseStringToDate("2016-11-23").getTime(); + if ("uri".equals(model.getQuery()) && startDate.getTime() >= date && endDate.getTime() > date) { + List apiInvokeStatisticalList = apiInvokeStatisticalService.findApiInvokeStatisticalList(model.getUserId(), startDate, endDate); + if (bos != null && apiInvokeStatisticalList.size() > 0) { + Map> resultMap = getCountByUri(apiInvokeStatisticalList); + for (StatAnalyBo boTemp : bos) { + String url = boTemp.getKey(); + boTemp.setSuccessEffectiveTime(resultMap.get(url).get("successEffectiveCount")); + boTemp.setSuccessInvalidTime(resultMap.get(url).get("successInvalidCount")); + boTemp.setDefeatTime(resultMap.get(url).get("defeatCount")); + if (apiUser != null) { + boTemp.setDeadline(apiUser.getDeadTime()); + } + long curVistedCount = apiVisitCountService.findApiVisitCountByDay(userId, url, DateUtil.truncateDay(new Date())); + long historyCount = apiVisitCountService.findApiVisitAllCount(userId, url, DateUtil.truncateDay(new Date())); + if (countMap != null && countMap.containsKey(url)) { + Integer totalCount = countMap.get(url); + long usedCount = curVistedCount + historyCount; + boTemp.setSurplusCallCount(Integer.valueOf((int) (totalCount - usedCount))); } } } - BasicModel basicModel = new BasicModel(200, "ok"); - basicModel.setResult(list); - mav.setModel(basicModel); - } else { - mav.setModel(new BasicModel(HttpStatusCodeEnum.BAD_REQUEST_ERROR_KEY)); } + List resources = openResourceService.findOpenResource(null); + Map urlMap = converMapData(resources); + for (StatAnalyBo boTemp : bos) { + List apiVisitCounts = apiVisitCountService.findAllApiVisitCount(model.getUserId(), boTemp.getKey(), startDate, endDate); + int total = 0; + for (ApiVisitCount apiVisitCount : apiVisitCounts) { + total += apiVisitCount.getVisitCount(); + } + boTemp.setBillingCount(total); + boTemp.setUrlName(urlMap.get(boTemp.getKey())); + boTemp.setUrl(boTemp.getKey()); + boTemp.setKey(null); + } + +// model.setResourceMap(converMapData(resources)); + model.setStatAnalyBoList(sortStatAnaly(bos)); + BasicModel basicModel = new BasicModel(200, "ok"); + basicModel.setResult(model); + mav.setModel(basicModel); return mav; } + private List createAnalyBosByLink(List analys) { + + + Map ret = new HashMap(); + Map> urlCodeMap = new HashMap>(); + int total = 0; + for (OpenUriAnaly openUriAnaly : analys) { + Integer temp = ret.get(openUriAnaly.getUrl()); + if (temp == null) { + ret.put(openUriAnaly.getUrl(), openUriAnaly.getUrlClickCount()); + } else { + ret.put(openUriAnaly.getUrl(), temp + openUriAnaly.getUrlClickCount()); + } + Map codeMap = urlCodeMap.get(openUriAnaly.getUrl()); + if (codeMap == null) { + codeMap = new HashMap(); + urlCodeMap.put(openUriAnaly.getUrl(), codeMap); + } + Map analyCodeMap = openUriAnaly.getCodeMap(); + for (String code : analyCodeMap.keySet()) { + Integer count = (Integer) analyCodeMap.get(code); + if ("200".equals(code)) { + Integer successCount = codeMap.get("successCount"); + if (successCount == null) { + codeMap.put("successCount", count); + } else { + codeMap.put("successCount", successCount + count); + } + } else { + Integer defeatCount = codeMap.get("defeatCount"); + if (defeatCount == null) { + codeMap.put("defeatCount", count); + } else { + codeMap.put("defeatCount", defeatCount + count); + } + } + } + total = total + openUriAnaly.getUrlClickCount(); + } + + List bos = new ArrayList(); + int index = 0; + double totalPercent = 0; + for (String url : ret.keySet()) { + Integer count = ret.get(url); + double percent = 0; + if (index + 1 == ret.size()) { + percent = 100 - totalPercent; + } else { + double a1 = count; + double val = a1 * 10000 / (double) total; + percent = DataUtil.roundDouble(val / 100, 2); + totalPercent = totalPercent + percent; + } + StatAnalyBo bo = new StatAnalyBo(); + bo.setKey(url); + bo.setCount(count); + bo.setPercent(percent); + Map codeMap = urlCodeMap.get(url); + bo.setSuccessTime(codeMap.get("successCount")); + bo.setDefeatTime(codeMap.get("defeatCount")); + if (codeMap.get("successCount") != null) { + bo.setSuccessRate(DataUtil.roundDouble((codeMap.get("successCount") * 100) / (double) count, 2)); + } + bos.add(bo); + + } + return bos; + } + + private List sortStatAnaly(List bos) { + Collections.sort(bos, new Comparator() { + @Override + public int compare(StatAnalyBo o1, StatAnalyBo o2) { + if (o1.getCount() > o2.getCount()) { + return -1; + } else if (o1.getCount() < o2.getCount()) { + return 1; + } + return 0; + } + }); + + return bos; + } + + private Map converMapData(List resources) { + Map map = new HashMap(); + for (OpenResource resource : resources) { + map.put(resource.getUri(), resource.getName()); + } + return map; + } + + + private Map> getCountByUri(List apiInvokeStatisticalList) { + Map> resultMap = new HashMap>(); + for (ApiInvokeStatistical apiInvokeStatistical : apiInvokeStatisticalList) { + Map detailMap = resultMap.get(apiInvokeStatistical.getRequestURI()); + if (detailMap == null) { + detailMap = new HashMap(); + resultMap.put(apiInvokeStatistical.getRequestURI(), detailMap); + } + Integer successEffectiveCount = detailMap.get("successEffectiveCount"); + Integer successInvalidCount = detailMap.get("successInvalidCount"); + Integer defeatCount = detailMap.get("defeatCount"); + Integer totalCount = detailMap.get("totalCount"); + if (successEffectiveCount != null) { + successEffectiveCount = successEffectiveCount + apiInvokeStatistical.getSuccessEffectiveTime(); + } else { + successEffectiveCount = apiInvokeStatistical.getSuccessEffectiveTime(); + } + if (successInvalidCount != null) { + successInvalidCount = successInvalidCount + apiInvokeStatistical.getSuccessInvalidTime(); + } else { + successInvalidCount = apiInvokeStatistical.getSuccessInvalidTime(); + ; + } + if (defeatCount != null) { + defeatCount = defeatCount + apiInvokeStatistical.getDefeatTime(); + } else { + defeatCount = apiInvokeStatistical.getDefeatTime(); + } + if (totalCount != null) { + totalCount = totalCount + apiInvokeStatistical.getTotalTime(); + } else { + totalCount = apiInvokeStatistical.getTotalTime(); + } + + detailMap.put("successEffectiveCount", successEffectiveCount); + detailMap.put("successInvalidCount", successInvalidCount); + detailMap.put("defeatCount", defeatCount); + detailMap.put("totalCount", totalCount); + } + + return resultMap; + } + + private String toChartString(List bos) { + JSONArray ja = new JSONArray(); + for (StatAnalyBo bo : bos) { + JSONArray array = new JSONArray(); + if (StringUtils.isNotBlank(bo.getKey())) { + if (bo.getKey().equals("level_0")) { + array.put("0s"); + } else if (bo.getKey().equals("level_1")) { + array.put("1sÒÔÏÂ"); + } else if (bo.getKey().equals("level_2")) { + array.put("1-2sÒÔÏÂ"); + } else if (bo.getKey().equals("level_3")) { + array.put("2-3sÒÔÏÂ"); + } else if (bo.getKey().equals("level_4")) { + array.put("3sÒÔÉÏ"); + } else if (bo.getKey().equals("level_100")) { + array.put("ÔÝÎÞÊý¾Ý"); + } else { + array.put(bo.getKey()); + } + } else { + array.put(bo.getUserId()); + } + + array.put(bo.getPercent()); + ja.put(array); + } + return ja.toString(); + } + public void setUserService(UserService userService) { this.userService = userService; } @@ -200,4 +456,12 @@ public class UsersController { public void setOpenUriAnalyService(OpenUriAnalyService openUriAnalyService) { this.openUriAnalyService = openUriAnalyService; } + + public void setApiUserService(ApiUserService apiUserService) { + this.apiUserService = apiUserService; + } + + public void setApiInvokeStatisticalService(ApiInvokeStatisticalService apiInvokeStatisticalService) { + this.apiInvokeStatisticalService = apiInvokeStatisticalService; + } } diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/weixin/DistrictController.java b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/weixin/DistrictController.java index 6ad4b19bc..442e4b77a 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/weixin/DistrictController.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/weixin/DistrictController.java @@ -6,6 +6,7 @@ import com.fangjia.dal.QueryParam; import com.fangjia.dal.SdQuery; import com.fangjia.dal.SrQuery; import com.fangjia.dal.common.DistrictKey; +import com.fangjia.dal.mongo.model.SeaweedImages; import com.fangjia.dal.seaweed.model.District; import com.fangjia.dal.sql.model.FjtUsers; import com.fangjia.open.compatible.model.JsonModel; @@ -18,6 +19,7 @@ import com.fangjia.service.bo.DistrictStatRentBo; import com.fangjia.service.datastore.DistrictService; import com.fangjia.service.district.DistrictStatRentService; import com.fangjia.service.district.DistrictStatService; +import com.fangjia.service.mongo.fangjia.SeaweedImagesService; import com.fangjia.service.sql.FjtUsersService; import com.fangjia.service.sql.UserCityService; import com.fangjia.service.user.UsersInfoService; @@ -44,7 +46,9 @@ public class DistrictController { private DistrictStatRentService districtStatRentService; private DistrictStatService districtStatService; private UserCityService userCityService; - private FjtUsersService fjtUsersService; + private FjtUsersService fjtUsersService; + + private SeaweedImagesService seaweedImagesService; /********************************************* new start *****************************************************/ /** @@ -55,14 +59,14 @@ public class DistrictController { * @param keyword * @return */ - public Object suggestAction( @Param(name = "city") String city, @Param(name = "cat") String cat, @Param(name = "keyword") String keyword, - @Param(name = "limit") Integer limit,@Param(name="lat")Double lat, @Param(name="lng")Double lng) { + public Object suggestAction(@Param(name = "city") String city, @Param(name = "cat") String cat, @Param(name = "keyword") String keyword, + @Param(name = "limit") Integer limit, @Param(name = "lat") Double lat, @Param(name = "lng") Double lng) { JsonModel model = new JsonModel(); if (limit == null || limit > 100 || limit <= 0) { limit = 10; } System.out.println(cat + "#" + city + "#" + keyword + "#" + limit + "#" + lng + "#" + lat); - List suggestList = getDistrictByKeyword(cat, city, keyword, limit, lng, lat); + List suggestList = getDistrictByKeyword(cat, city, keyword, limit, lng, lat); model.setJsonModel(suggestList); return model; } @@ -75,25 +79,30 @@ public class DistrictController { String login_user_type = CookieUtils.getCookieValue(request, "login_user_type"); //±£´æÆóÒµÓû§Ñ¡ÔñµÄ³ÇÊÐ,ÆóÒµÓû§7Ìì - String weiXinId = CookieUtils.getCookieValue(request,"we_chat_open_id"); + String weiXinId = CookieUtils.getCookieValue(request, "we_chat_open_id"); // if(StringUtils.isBlank(login_user_type) || StringUtils.isBlank(weiXinId)){ // response.sendRedirect("/coming"); // return null; // } - if("b".equals(login_user_type) || "gb".equals(login_user_type)){ - CacheUtils.putValue(CachePolicyEnum.LONG, UsersInfoService.class, weiXinId + "_city_"+ login_user_type , model.getCityName()); - } - Long userId = Long.parseLong(CookieUtils.getCookieValue(request,"login_user_id")); - if(userId != null){ - FjtUsers users = fjtUsersService.findById(userId); - if(users != null){ - model.setRole(users.getRole()); - } - } + if ("b".equals(login_user_type) || "gb".equals(login_user_type)) { + CacheUtils.putValue(CachePolicyEnum.LONG, UsersInfoService.class, weiXinId + "_city_" + login_user_type, model.getCityName()); + } + try { + Long userId = Long.parseLong(CookieUtils.getCookieValue(request, "login_user_id")); + if (userId != null) { + FjtUsers users = fjtUsersService.findById(userId); + if (users != null) { + model.setRole(users.getRole()); + } + } + } catch (Exception ex) { + + } model.setType(login_user_type); return model; } + private List getDistrictByKeyword(String cat, String city, String keyword, int limit, final Double lng, final Double lat) { keyword = DataUtil.escapeSolr(keyword); @@ -109,14 +118,14 @@ public class DistrictController { BooleanQuery srQuery1 = new BooleanQuery(); BooleanQuery nameQuery = new BooleanQuery(); - // nameQuery.add(new TermQuery(new Term("district_name", keyword)), BooleanClause.Occur.SHOULD); - // nameQuery.add(new TermQuery(new Term("alias_std", keyword)), BooleanClause.Occur.SHOULD); - // nameQuery.add(new TermQuery(new Term("address", keyword)), BooleanClause.Occur.SHOULD); - // nameQuery.add(new TermQuery(new Term("addr_alias_std", keyword)), BooleanClause.Occur.SHOULD); + // nameQuery.add(new TermQuery(new Term("district_name", keyword)), BooleanClause.Occur.SHOULD); + // nameQuery.add(new TermQuery(new Term("alias_std", keyword)), BooleanClause.Occur.SHOULD); + // nameQuery.add(new TermQuery(new Term("address", keyword)), BooleanClause.Occur.SHOULD); + // nameQuery.add(new TermQuery(new Term("addr_alias_std", keyword)), BooleanClause.Occur.SHOULD); nameQuery.add(new TermQuery(new Term("keyword", keyword)), BooleanClause.Occur.SHOULD); //nameQuery.add(new TermQuery(new Term("keyword_cjk", keyword)), BooleanClause.Occur.SHOULD);//Õâ¸öÖØÒª£¬Òòseaweed²»Ö§³ÖÄ£ºýËÑË÷£¬µ±ÊäÈë"ÖÐÔ¶Á½"ÐèÓô˽øÐÐËÑË÷ srQuery1.add(nameQuery, BooleanClause.Occur.SHOULD); - if(lat != null && lng != null && lat != 0 && lng != 0){ + if (lat != null && lng != null && lat != 0 && lng != 0) { Map geo = GeocodeUtils.geoconvBaiduToGoogle(lng, lat); SdQuery sdQuery = new SdQuery(); sdQuery.setPoint(geo.get("lat") + "," + geo.get("lng")); @@ -125,7 +134,7 @@ public class DistrictController { params.add(new QueryParam(QueryParam.SD_PARAM_NAME, sdQuery)); } params.add(new QueryParam("$sr", new SrQuery(srQuery1))); - List districts = districtService.findAllByParams(params, 0, limit, new String[]{"region", "name", "address", "addrAlias","id"}); + List districts = districtService.findAllByParams(params, 0, limit, new String[]{"region", "name", "address", "addrAlias", "id", "alias"}); List ret = new ArrayList(districts.size()); for (District district : districts) { AutoCompleteBo bo = new AutoCompleteBo(); @@ -134,24 +143,34 @@ public class DistrictController { bo.setDesc(district.getAddress()); bo.setRegion(district.getRegion()); bo.setId(district.getId()); + if (!district.getName().contains(keyword)) { + if (district.getAlias() != null && !district.getAlias().isEmpty()) { + for (String alias : district.getAlias()) { + if (alias.contains(keyword)){ + bo.setAlias(alias); + break; + } + } + } + } ret.add(bo); } return ret; } - public Object districtDetailAction(DistrictModel districtModel,HttpServletRequest request,HttpServletResponse response) { + public Object districtDetailAction(DistrictModel districtModel, HttpServletRequest request, HttpServletResponse response) { //idºÍname²»ÄÜͬʱΪ¿Õ - if(StringUtils.isBlank(districtModel.getId()) && (StringUtils.isBlank(districtModel.getCityName()) || StringUtils.isBlank(districtModel.getName()))) { + if (StringUtils.isBlank(districtModel.getId()) && (StringUtils.isBlank(districtModel.getCityName()) || StringUtils.isBlank(districtModel.getName()))) { districtModel.setMsg("²ÎÊý´íÎó"); return districtModel; } District district = null; - if(StringUtils.isNotBlank(districtModel.getId())) { + if (StringUtils.isNotBlank(districtModel.getId())) { district = districtService.findById(districtModel.getId()); - if(district != null) { + if (district != null) { districtModel.setCityName(district.getCity()); districtModel.setRegion(district.getRegion()); districtModel.setName(district.getName()); @@ -167,24 +186,26 @@ public class DistrictController { String userId = CookieUtils.getCookieValue(request, "login_user_id"); - //Ð¡Çø×â½ð List districtStatRentBos = districtStatRentService.findAllHouseTypeByDistrictStatRent(new DistrictKey(district)); //´¦ÀíͼƬÁ´½Ó - List outPics = Lists.newArrayList(); - if(district.getOutPics() != null) { - for (String outPic : district.getOutPics()) { -// outPics.add(districtModel.getPicUrl() + DataUtil.encodePicUrl(outPic, "s", "district")); - outPics.add("http://static.fangjia.com/stc/fs/" + DataUtil.encodePicUrl(outPic, "s", "district")); - } +// List outPics = Lists.newArrayList(); +// if(district.getOutPics() != null) { +// for (String outPic : district.getOutPics()) { +//// outPics.add(districtModel.getPicUrl() + DataUtil.encodePicUrl(outPic, "s", "district")); +// outPics.add("http://static.fangjia.com/stc/fs/" + DataUtil.encodePicUrl(outPic, "s", "district")); +// } +// } + SeaweedImages seaweedImages = seaweedImagesService.findById(district.getId()); + if (seaweedImages != null) { + district.setOutPics(seaweedImages.getOutPics()); } - district.setOutPics(outPics); districtModel.setDistrict(district); districtModel.setDistrictStatBo(districtStatBo); districtModel.setDistrictStatRentBos(districtStatRentBos); - String city=request.getParameter("city"); - boolean is=true; + String city = request.getParameter("city"); + boolean is = true; if (null != districtStatBo && null != districtStatBo.getDefaultDistrictStat()) { double credit = districtStatBo.getDefaultDistrictStat().getCredit(); @@ -203,7 +224,7 @@ public class DistrictController { } else { is = true; } - if(!is){ + if (!is) { try { response.sendRedirect("wrongPrice"); } catch (Exception e) { @@ -213,7 +234,6 @@ public class DistrictController { } - private DistrictStatBo getDistrictStat(DistrictKey districtKey) { District district = districtService.findDistrict(districtKey, true); DistrictStatBo statBo = null; @@ -227,8 +247,8 @@ public class DistrictController { // ͬ±ÈÊý¾Ý if (statBo != null) { Date date = DateUtil.getThisWeekInLastYear(); - Date[] dateList = { DateUtil.getBeforeDay(date, 14), DateUtil.getBeforeDay(date, 7), DateUtil.getAfterDay(date, 7), - DateUtil.getAfterDay(date, 14), date }; + Date[] dateList = {DateUtil.getBeforeDay(date, 14), DateUtil.getBeforeDay(date, 7), DateUtil.getAfterDay(date, 7), + DateUtil.getAfterDay(date, 14), date}; DistrictStatBo yearPeriodStatBo = null; Integer markup = Integer.MAX_VALUE; @@ -318,9 +338,11 @@ public class DistrictController { this.userCityService = userCityService; } - public void setFjtUsersService(FjtUsersService fjtUsersService) { - this.fjtUsersService = fjtUsersService; - } - - + public void setFjtUsersService(FjtUsersService fjtUsersService) { + this.fjtUsersService = fjtUsersService; + } + + public void setSeaweedImagesService(SeaweedImagesService seaweedImagesService) { + this.seaweedImagesService = seaweedImagesService; + } } diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/weixin/DistrictTrendController.java b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/weixin/DistrictTrendController.java index 3005fcf82..18c8f0bbe 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/weixin/DistrictTrendController.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/weixin/DistrictTrendController.java @@ -559,7 +559,7 @@ public class DistrictTrendController { DistrictStat ds = districtStatMap.get(key); JSONArray ja = new JSONArray(); ja.put(DateUtil.getBeforeDay(ds.getWeekend(), -1).getTime()); - ja.put(ds.getAvgPrice()); + ja.put(ds.getAvg_price_2b()); districtJa.put(ja); } @@ -567,7 +567,7 @@ public class DistrictTrendController { DistrictStat ds = villaDistrictStatMap.get(key); JSONArray ja = new JSONArray(); ja.put(DateUtil.getBeforeDay(ds.getWeekend(), -1).getTime()); - ja.put(ds.getAvgPrice()); + ja.put(ds.getAvg_price_2b()); villaJa.put(ja); } diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/weixin/UserController.java b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/weixin/UserController.java index 73e27d8a6..460a95e78 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/weixin/UserController.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/weixin/UserController.java @@ -65,6 +65,10 @@ public class UserController { return model; } + public Object aiLoginPageAction(UserModel model) { + return model; + } + //²³º£ÒøÐеǼ public Object bhydLoginPageAction(UserModel model, HttpServletResponse response, HttpServletRequest request) { String type = StringUtils.trimToNull(model.getType()); @@ -263,11 +267,22 @@ public class UserController { try { FjtUsers user = usersInfoService.getUser(mobile); if(user == null) { - long userId = usersInfoService.addUser(mobile, "", weiXinId); - if(userId == 0){ - return resultModel; + String cookieUserId = CookieUtils.getCookieValue(request, "login_user_id"); + if(StringUtils.isNotBlank(cookieUserId)){ + long userId = Long.valueOf(cookieUserId); + user = fjtUsersService.findById(Long.valueOf(userId)); } - CookieUtils.setCookie("login_user_id", userId + "", "/", 60 * 60 * 24 *7, response); + if(user!=null){ + usersInfoService.bindWeiXin(weiXinId, user.getId()); + CookieUtils.setCookie("login_user_id", user.getId() + "", "/", 60 * 60 * 24 *7, response); + }else{ + long userId = usersInfoService.addUser(mobile, "", weiXinId); + if(userId == 0){ + return resultModel; + } + CookieUtils.setCookie("login_user_id", userId + "", "/", 60 * 60 * 24 *7, response); + } + } else { usersInfoService.bindWeiXin(weiXinId, user.getId()); CookieUtils.setCookie("login_user_id", user.getId() + "", "/", 60 * 60 * 24 *7, response); @@ -296,6 +311,14 @@ public class UserController { String pass = StringUtils.trimToNull(model.getPass()); String weiXinId = CookieUtils.getCookieValue(request,"we_chat_open_id"); + String source = model.getSource(); + + // AI¹À¼ÛС³ÌÐò + if ("ai-price-mp".equals(source)) { + model.setAppId("wx30979dc8c24a82b6"); + model.setAppSecret("ec013ae42882368bf3b157545042249a"); + } + if(StringUtils.isBlank(weiXinId) && StringUtils.isNotBlank(model.getCode())){ System.out.println("С³ÌÐòcode:"+model.getCode()); System.out.println("С³ÌÐòAppId:"+model.getAppId()); diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/weixin/WeiXinEvaluationController.java b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/weixin/WeiXinEvaluationController.java index 716c2156f..2607ac3dc 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/weixin/WeiXinEvaluationController.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/weixin/WeiXinEvaluationController.java @@ -763,6 +763,27 @@ public class WeiXinEvaluationController { } return model; } + + // ¾ù¼Û¶Ô±È½Ó¿Ú(·¿¼ÛͨС³ÌÐòÓÃ) + public Object otherSourcePlusAction(EvaluationModel model){ + + JsonModel jsonMmodel = new JsonModel(); + Map dataMap = new HashMap(); + if(StringUtils.isNotBlank(model.getCityName()) && StringUtils.isNotBlank(model.getRegion()) && StringUtils.isNotBlank(model.getName()) && model.getBuildType() != null){ + String category = getEnCategory(model.getBuildType()); + AverageStatistics averageStatistics = averageStatisticsService.findOneAverageStatictics(model.getCityName(), model.getName(), category); + + Integer tradeAvgPrice = dealPriceService.findDealPrices(model.getCityName(), model.getRegion(), model.getName(), DateUtil.getFirstDayOfMonth(new Date(), -6), DateUtil.getFirstDayOfMonth(new Date(), 0)); + //columnX = "['³É½»¾ù¼Û(½ü°ëÄê)','·¿¼ÛÍø¹ÒÅÆ¾ù¼Û','ËÑ·¿¹ÒÅÆ¾ù¼Û','°²¾Ó¿Í¹ÒÅÆ¾ù¼Û']"; + dataMap.put("dealPrice", tradeAvgPrice); + dataMap.put("fjw", averageStatistics.getFangjiaPrice()); + dataMap.put("soufang", averageStatistics.getSoufangEsfPrice()); + dataMap.put("anjuke", averageStatistics.getAnjukeEsfPrice()); + } + jsonMmodel.setJsonModel(dataMap); + return jsonMmodel; + } + //¾ù¼Û¶Ô±È public Object otherSourceAction(EvaluationModel model){ diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/dto/addressGovernance/DistrictDto.java b/projects/fangjia-open/src/main/java/com/fangjia/open/dto/addressGovernance/DistrictDto.java index cc71dcf21..8f99dee2a 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/dto/addressGovernance/DistrictDto.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/dto/addressGovernance/DistrictDto.java @@ -7,6 +7,7 @@ public class DistrictDto { private String region; private String name; private String address; + private String district; public String getProvince() { return province; @@ -47,4 +48,12 @@ public class DistrictDto { public void setAddress(String address) { this.address = address; } + + public String getDistrict() { + return district; + } + + public void setDistrict(String district) { + this.district = district; + } } \ No newline at end of file diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/exceptionhander/FangjiaOpenExceptionHandler.java b/projects/fangjia-open/src/main/java/com/fangjia/open/exceptionhander/FangjiaOpenExceptionHandler.java index 8701acb19..7848e9b25 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/exceptionhander/FangjiaOpenExceptionHandler.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/exceptionhander/FangjiaOpenExceptionHandler.java @@ -1,14 +1,21 @@ package com.fangjia.open.exceptionhander; import java.io.IOException; +import java.net.InetAddress; +import java.net.UnknownHostException; import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import com.fangjia.core.util.DingDingMessageUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sothis.web.mvc.ActionContext; import org.sothis.web.mvc.ExceptionHandler; - +import java.net.Inet4Address; +import java.net.NetworkInterface; +import java.net.SocketException; +import java.util.Enumeration; public class FangjiaOpenExceptionHandler implements ExceptionHandler { private static final Logger LOGGER = LoggerFactory.getLogger(FangjiaOpenExceptionHandler.class); @@ -17,9 +24,42 @@ public class FangjiaOpenExceptionHandler implements ExceptionHandler { LOGGER.error("", e); } ActionContext context = ActionContext.getContext(); + + String ip = getLocalHostIP(); + String token = "2307d2fec8314b3e8b4b83dd1d42da2e2051638e3e668f21e77ca01258bf682c"; + try { + DingDingMessageUtil.sendTextMessage(token, "[OpenApi] "+ip+"·þÎñÆ÷ÄÚ²¿´íÎó£¬Ç뼰ʱ¹Ø×¢£¡"); + } catch (Exception e1) { + e1.printStackTrace(); + } context.getResponse().setStatus(500); context.getResponse().setCharacterEncoding("UTF-8"); context.getResponse().setContentType("application/json;charset=UTF-8"); context.getResponse().getWriter().println("{\"code\":500, \"msg\":\"·þÎñÆ÷ÄÚ²¿´íÎó\"}"); } + + public static String getLocalHostIP() { + /*k8sϵͳÉÏÔËÐÐʱ,ʹÓÃhostnameÇø·Ö*/ + if ("true".equalsIgnoreCase(System.getenv("ON_K8S"))) { + return System.getenv("HOSTNAME"); + } + String result = null; + try { + Enumeration enumeration = NetworkInterface.getNetworkInterfaces(); + InetAddress ip; + while (enumeration.hasMoreElements()) { + NetworkInterface netInterface = (NetworkInterface) enumeration.nextElement(); + Enumeration addresses = netInterface.getInetAddresses(); + while (addresses.hasMoreElements()) { + ip = (InetAddress) addresses.nextElement(); + if (ip != null && ip instanceof Inet4Address && (ip.getHostAddress().contains("192.168.0") || ip.getHostAddress().contains("192.168.10"))) { + result = ip.getHostAddress(); + } + } + } + } catch (SocketException e) { + e.printStackTrace(); + } + return result == null ? "192.168.20.6" : result; + } } diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/interceptors/AuthenticationInterceptor.java b/projects/fangjia-open/src/main/java/com/fangjia/open/interceptors/AuthenticationInterceptor.java index eff33a38f..c04cab406 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/interceptors/AuthenticationInterceptor.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/interceptors/AuthenticationInterceptor.java @@ -3,6 +3,7 @@ package com.fangjia.open.interceptors; import com.fangjia.core.RegionData; import com.fangjia.core.util.AnalyticsUtil; import com.fangjia.core.util.DateUtil; +import com.fangjia.core.util.DingDingMessageUtil; import com.fangjia.dal.common.ServerAreaData; import com.fangjia.dal.mongo.fangjia.model.ServerArea; import com.fangjia.dal.mongo.open.model.ApiUserAuthority; @@ -14,6 +15,7 @@ import com.fangjia.open.model.RestfulModelAndView; import com.fangjia.service.open.ApiUserAuthorityService; import com.fangjia.service.open.ApiVisitCountService; import com.fangjia.service.sql.ApiUserService; +import com.fangjia.service.util.kafka.KafkaProducerUtils; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -24,428 +26,508 @@ import org.sothis.web.mvc.Interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import java.net.Inet4Address; +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.net.SocketException; import java.util.*; /** * APIÀ¹½ØÆ÷ * * @author - * */ public class AuthenticationInterceptor implements Interceptor { - private ApiUserService apiUserService; - private ApiUserAuthorityService apiUserAuthorityService; - private ApiVisitCountService apiVisitCountService; - private static final Logger LOGGER = LoggerFactory.getLogger(AuthenticationInterceptor.class); - private static final Date OLD_USER_SPLITTED_DATE = DateUtil.parseFormatDate("2016-06-06"); - private static final List HAS_SUB_SERVICE_URIS = new ArrayList(); - private static final String SUB_SERVICE_SEPARATOR = "#"; - private static final String SERVICE_CODE_PARAM_NAME = "serviceCode"; - static { - HAS_SUB_SERVICE_URIS.add("/property/transaction"); - } - /** - * token¹ýÆÚʱ¼ä µ¥Î»:s - */ - private static final long TOKEN_EXPIRED_TIME = 60 * 60 * 2; + private ApiUserService apiUserService; + private KafkaProducerUtils kafkaProducerUtils; + private ApiUserAuthorityService apiUserAuthorityService; + private ApiVisitCountService apiVisitCountService; + private static final Logger LOGGER = LoggerFactory.getLogger(AuthenticationInterceptor.class); + private static final Date OLD_USER_SPLITTED_DATE = DateUtil.parseFormatDate("2016-06-06"); + private static final List HAS_SUB_SERVICE_URIS = new ArrayList(); + private static final String SUB_SERVICE_SEPARATOR = "#"; + private static final String SERVICE_CODE_PARAM_NAME = "serviceCode"; + private static final String SMS_DATA_TOPIC = "sms-data-topic"; + private static final String SMS_DATA_TOPIC_PROFIX = "sendSms90-"; - public Object intercept(ActionInvocation invocation) throws ActionInvocationException { + static { + HAS_SUB_SERVICE_URIS.add("/property/transaction"); + } - Authority authority = getAuthority(invocation); - ActionContext context = invocation.getActionContext(); - HttpServletRequest request = context.getRequest(); - RestfulModelAndView ret = new RestfulModelAndView(); - ret.setViewType("rest"); - - try { - HttpCode httpCode = null; - if(!OpenConfig.getConfig().isOpenAllAuthority()) { - String token = request.getParameter("token"); - if(isNeedToken(authority)){ - httpCode = authorized(token, request); - }else if(StringUtils.isNotBlank(token)){ - ApiUser apiUser = parseApiUserByToken(FangjiaApiUtil.parse2Token(token)); - if(apiUser != null){ - User user = apiUserService.findUserById(apiUser.getId()); - AuthenticationBean.get(request, apiUser, user, null); - } - } - } - //¹¦ÄÜ·½·¨Ã»ÓÐÉèÖÃȨÏÞ»òÕßÓи÷½·¨È¨ÏÞ - if (authority == null || authority.role() == Role.NONE || null == httpCode) { - Object obj; - try{ - obj = invocation.invoke(); - }catch (Exception e){ - throw e; - } - return obj; - }else { - if(httpCode.getErrorCode() == 4003){ - BasicModel basicModel = BasicModel.buildBadRequestModel(httpCode.getErrorMessage().toString()); - ret.setModel(basicModel); - return ret; - }else{ - String msg = httpCode.getMessage() + "(" + httpCode.getErrorMessage() + ")"; - BasicModel basicModel = BasicModel.buildUnAuthorizedModel().setMsg(msg); - ret.setModel(basicModel); - return ret; - } - - } - } catch (Exception e) { - LOGGER.error("Authentication error : ", e); - ret.setModel(BasicModel.buildServerErrorModel()); - ret.setViewParam("code", HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - return ret; - } - - } - - private boolean isNeedToken(Authority authority){ - return authority != null && authority.role() != null && authority.role() != Role.NONE; - } - - private boolean isReachUpperLimit(ApiUserAuthority auth, String uri, String serviceCode) { - - if (auth == null || auth.getLimitCountMap() == null) { - return false; - } - Date visitDate = DateUtil.truncateDay(new Date()); - Integer upperLimit = auth.getLimitCountMap().get(uri); - Long apiVisitCount; - if (upperLimit != null && upperLimit > 0) { - apiVisitCount = apiVisitCountService.findApiVisitCount(auth.getUserId(), uri, null, visitDate); - if(apiVisitCount >= upperLimit){ - return true; - } - } - if(hasSubService(uri) && StringUtils.isNotBlank(serviceCode)){ - upperLimit = auth.getLimitCountMap().get(uri + SUB_SERVICE_SEPARATOR + serviceCode); - if (upperLimit != null && upperLimit > 0) { - apiVisitCount = apiVisitCountService.findApiVisitCount(auth.getUserId(), uri, serviceCode, visitDate); - if(apiVisitCount >= upperLimit){ - return true; - } - } - } - return false; - } - - private boolean isReachDeadline(ApiUserAuthority auth, String uri, String serviceCode){ - - if(auth.getDeadlineMap() == null){ - return false; - } - Date deadline = auth.getDeadlineMap().get(uri); - if(null != deadline && deadline.before(new Date())){ - return true; - } - if(hasSubService(uri) && StringUtils.isNotBlank(serviceCode)){ - deadline = auth.getDeadlineMap().get(uri + SUB_SERVICE_SEPARATOR + serviceCode); - if(null != deadline && deadline.before(new Date())){ - return true; - } - } - - return false; - } - - private boolean isReachSumLimit(ApiUserAuthority auth, String uri, String serviceCode) { - - if (auth == null || auth.getTotalCountMap() == null) { - return false; - } - - if(auth.getTotalCountMap() != null && auth.getTotalCountMap().get(uri) != null){ - Integer totalLimit = auth.getTotalCountMap().get(uri); - Long totalApiVisitCount; - if(totalLimit != null && totalLimit > 0){ - totalApiVisitCount = apiVisitCountService.findApiVisitTotalCount(auth.getUserId(), uri, serviceCode); - if(totalApiVisitCount >= totalLimit){ - return true; - } - } - } - if(hasSubService(uri) && StringUtils.isNotBlank(serviceCode)){ - Integer totalLimit = auth.getTotalCountMap().get(uri + SUB_SERVICE_SEPARATOR + serviceCode); - if(totalLimit != null && totalLimit > 0){ - Long totalApiVisitCount = apiVisitCountService.findApiVisitTotalCount(auth.getUserId(), uri, serviceCode); - if(totalApiVisitCount >= totalLimit){ - return true; - } - } - - } - return false; - } - - private Authority getAuthority(ActionInvocation invocation) { - Authority authority; - // »ñÈ¡·½·¨ÉϵÄȨÏÞ×¢½â - authority = invocation.getAction().getActionMethod().getAnnotation(Authority.class); - if (null != authority) { - return authority; - } - // »ñÈ¡ÀàÉϵÄȨÏÞ×¢½â - authority = invocation.getControllerInstance().getClass().getAnnotation(Authority.class); - return authority; - } - - - /** - * ¼ìÑéÊÇ·ñÓзÃÎʸÃActionµÄȨÏÞ - * - * @param tokenStr - * @param request - * @return - * @throws Exception - */ - private HttpCode authorized(String tokenStr, HttpServletRequest request) throws Exception { - - // ¼ì²éÊÇ·ñΪapiÓû§ - HttpCode ret = new HttpCode(OpenHttpCodeEnum.AUTH_FAILD); - Token token = FangjiaApiUtil.parse2Token(tokenStr); - ApiUser apiUser = parseApiUserByToken(token); - if (null == apiUser) { - return ret; - } - if(apiUser.getDeadTime() != null && DateUtil.truncateDay(new Date()).after(apiUser.getDeadTime())){ - return new HttpCode(OpenHttpCodeEnum.USER_EXPIRED); - } - if(!isOldUser(apiUser) && isExpired(token)){ - return new HttpCode(OpenHttpCodeEnum.TOKEN_EXPIRED); - } - if (1 == apiUser.getStatus()) { - return new HttpCode(OpenHttpCodeEnum.AUTH_FAILD, "ÄãµÄÕË»§ÒÑʧЧ"); - } - if(StringUtils.isNotBlank(apiUser.getIp())){ - String ip = AnalyticsUtil.getIpAddress(request); - if(!isAuthIp(ip,apiUser)){ - ret = new HttpCode(OpenHttpCodeEnum.AUTH_FAILD,"ip[" + ip + "]ÎÞȨÏÞ·ÃÎÊAPI"); - return ret; - } - } - - String uri = request.getRequestURI(); - ApiUserAuthority auth = this.apiUserAuthorityService.findByUserId(apiUser.getId()); - if(auth != null){ - User user = apiUserService.findUserById(apiUser.getId()); - AuthenticationBean.get(request, apiUser, user, auth); - } - uri = OpenConfig.getConfig().isDevelopmentEnvironment() ? uri.replace("/fangjia-open", "") : uri; - // ¼ì²éÊÇ·ñÓзÃÎʸÃActionµÄȨÏÞ - boolean authAction = null != auth && auth.getOpenResourseUris().contains(uri); - String cityName = request.getParameter("city"); - if(StringUtils.isBlank(cityName)){ - cityName = request.getParameter("cityName"); - } - if (StringUtils.isNotBlank(cityName)) { - boolean authCity = StringUtils.isNotBlank(apiUser.getCity()) && !StringUtils.equalsIgnoreCase(apiUser.getCity(), "all"); - if(authCity){ - cityName = request.getParameter("city"); - cityName = RegionData.formatCity(cityName); - if(!RegionData.isCity(cityName)){ - ret = new HttpCode(OpenHttpCodeEnum.ARGUMENT_INVALID); - ret.setErrorMessage("³ÇÊзǷ¨"); - return ret; - } - } - } - boolean authCity = isAuthCity(cityName, apiUser); - if (!authCity) { - ret = new HttpCode(OpenHttpCodeEnum.AUTH_FAILD, "Äúδ¿ªÍ¨³ÇÊÐ" + (StringUtils.isNotBlank(cityName) ? cityName : StringUtils.EMPTY) + "µÄȨÏÞ"); - } - if (authAction && authCity) { - if(hasSubService(uri)){ - List serviceCodes = getServiceCode(request); - for(String serviceCode : serviceCodes){ - if(!auth.getOpenResourseUris().contains(uri + SUB_SERVICE_SEPARATOR + serviceCode)){ - ret = new HttpCode(OpenHttpCodeEnum.AUTH_FAILD ,"ÎÞȨÏÞ·ÃÎÊ·þÎñ:" + serviceCode); - return ret; - } - if(isReachDeadline(auth, uri, serviceCode)){ - ret = new HttpCode(OpenHttpCodeEnum.SERVICE_EXPIRED, serviceCode + "·þÎñÒѹýÆÚ"); - return ret; - } - if(isReachUpperLimit(auth, uri, serviceCode)){ - ret = new HttpCode(OpenHttpCodeEnum.UPPER_LIMIT ,serviceCode + "½ñÈÕÒÑ´ïµ½Åä¶îÉÏÏÞ"); - return ret; - } - // ¼ì²âÊÇ·ñ´ïµ½×ÜÊý·ÃÎÊÉÏÏÞ - if (isReachSumLimit(auth, uri, serviceCode)) { - ret = new HttpCode(OpenHttpCodeEnum.UPPER_LIMIT, serviceCode + "ÒÑ´ïµ½Åä¶îÉÏÏÞ"); - return ret; - } - } - - }else{ - if(isReachDeadline(auth, uri, null)){ - ret = new HttpCode(OpenHttpCodeEnum.UPPER_LIMIT, "·þÎñÒѹýÆÚ"); - return ret; - } - // ¼ì²âÊÇ·ñ´ïµ½½ñÌì·ÃÎÊÉÏÏÞ - if (isReachUpperLimit(auth, uri, null)) { - ret = new HttpCode(OpenHttpCodeEnum.UPPER_LIMIT, "½ñÈÕÒÑ´ïµ½Åä¶îÉÏÏÞ"); - return ret; - } - // ¼ì²âÊÇ·ñ´ïµ½×ÜÊý·ÃÎÊÉÏÏÞ - if (isReachSumLimit(auth, uri, null)) { - ret = new HttpCode(OpenHttpCodeEnum.UPPER_LIMIT, "ÒÑ´ïµ½Åä¶îÉÏÏÞ"); - return ret; - } - } - return null; - } - - return ret; - } - - - - /** - * - * @param request - * @return + /** + * token¹ýÆÚʱ¼ä µ¥Î»:s */ - private List getServiceCode(HttpServletRequest request){ + private static final long TOKEN_EXPIRED_TIME = 60 * 60 * 2; - String serviceCode = request.getParameter(SERVICE_CODE_PARAM_NAME); - if(StringUtils.isBlank(serviceCode)){ - return Collections.emptyList(); - } - return Arrays.asList(serviceCode.split(",|£¬")); - } - /** - * ÅжϸÃAPIÊÇ·ñÓµÓÐ×ÓȨÏÞ - * @param uri - * @return + public Object intercept(ActionInvocation invocation) throws ActionInvocationException { + + Authority authority = getAuthority(invocation); + ActionContext context = invocation.getActionContext(); + HttpServletRequest request = context.getRequest(); + RestfulModelAndView ret = new RestfulModelAndView(); + ret.setViewType("rest"); + + try { + HttpCode httpCode = null; + if (!OpenConfig.getConfig().isOpenAllAuthority()) { + String token = request.getParameter("token"); + if (isNeedToken(authority)) { + httpCode = authorized(token, request); + } else if (StringUtils.isNotBlank(token)) { + ApiUser apiUser = parseApiUserByToken(FangjiaApiUtil.parse2Token(token)); + if (apiUser != null) { + User user = apiUserService.findUserById(apiUser.getId()); + AuthenticationBean.get(request, apiUser, user, null); + } + } + } + //¹¦ÄÜ·½·¨Ã»ÓÐÉèÖÃȨÏÞ»òÕßÓи÷½·¨È¨ÏÞ + if (authority == null || authority.role() == Role.NONE || null == httpCode) { + Object obj; + try { + obj = invocation.invoke(); + } catch (Exception e) { + throw e; + } + return obj; + } else { + if (httpCode.getErrorCode() == 4003) { + BasicModel basicModel = BasicModel.buildBadRequestModel(httpCode.getErrorMessage().toString()); + ret.setModel(basicModel); + return ret; + } else { + String msg = httpCode.getMessage() + "(" + httpCode.getErrorMessage() + ")"; + BasicModel basicModel = BasicModel.buildUnAuthorizedModel().setMsg(msg); + ret.setModel(basicModel); + return ret; + } + + } + } catch (Exception e) { + String ip = getLocalHostIP(); + String token = "2307d2fec8314b3e8b4b83dd1d42da2e2051638e3e668f21e77ca01258bf682c"; + try { + DingDingMessageUtil.sendTextMessage(token, "[OpenApi] "+ip+"Authentication error£¡"); + } catch (Exception e1) { + e1.printStackTrace(); + } + LOGGER.error("Authentication error : ", e); + ret.setModel(BasicModel.buildServerErrorModel()); + ret.setViewParam("code", HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + return ret; + } + } + + private static String getLocalHostIP() { + /*k8sϵͳÉÏÔËÐÐʱ,ʹÓÃhostnameÇø·Ö*/ + if ("true".equalsIgnoreCase(System.getenv("ON_K8S"))) { + return System.getenv("HOSTNAME"); + } + String result = null; + try { + Enumeration enumeration = NetworkInterface.getNetworkInterfaces(); + InetAddress ip; + while (enumeration.hasMoreElements()) { + NetworkInterface netInterface = (NetworkInterface) enumeration.nextElement(); + Enumeration addresses = netInterface.getInetAddresses(); + while (addresses.hasMoreElements()) { + ip = (InetAddress) addresses.nextElement(); + if (ip != null && ip instanceof Inet4Address && (ip.getHostAddress().contains("192.168.0") || ip.getHostAddress().contains("192.168.10"))) { + result = ip.getHostAddress(); + } + } + } + } catch (SocketException e) { + e.printStackTrace(); + } + return result == null ? "192.168.20.6" : result; + } + + private boolean isNeedToken(Authority authority) { + return authority != null && authority.role() != null && authority.role() != Role.NONE; + } + + private boolean isReachUpperLimit(ApiUserAuthority auth, String uri, String serviceCode) { + + if (auth == null || auth.getLimitCountMap() == null) { + return false; + } + Date visitDate = DateUtil.truncateDay(new Date()); + Integer upperLimit = auth.getLimitCountMap().get(uri); + Long apiVisitCount; + if (upperLimit != null && upperLimit > 0) { + apiVisitCount = apiVisitCountService.findApiVisitCount(auth.getUserId(), uri, null, visitDate); + if (apiVisitCount >= upperLimit) { + return true; + } + } + if (hasSubService(uri) && StringUtils.isNotBlank(serviceCode)) { + upperLimit = auth.getLimitCountMap().get(uri + SUB_SERVICE_SEPARATOR + serviceCode); + if (upperLimit != null && upperLimit > 0) { + apiVisitCount = apiVisitCountService.findApiVisitCount(auth.getUserId(), uri, serviceCode, visitDate); + if (apiVisitCount >= upperLimit) { + return true; + } + } + } + return false; + } + + private boolean isReachDeadline(ApiUserAuthority auth, String uri, String serviceCode) { + + if (auth.getDeadlineMap() == null) { + return false; + } + Date deadline = auth.getDeadlineMap().get(uri); + if (null != deadline && deadline.before(new Date())) { + return true; + } + if (hasSubService(uri) && StringUtils.isNotBlank(serviceCode)) { + deadline = auth.getDeadlineMap().get(uri + SUB_SERVICE_SEPARATOR + serviceCode); + if (null != deadline && deadline.before(new Date())) { + return true; + } + } + + return false; + } + + private boolean isReachSumLimit(ApiUserAuthority auth, String uri, String serviceCode) { + + if (auth == null || auth.getTotalCountMap() == null) { + return false; + } + + if (auth.getTotalCountMap() != null && auth.getTotalCountMap().get(uri) != null) { + Integer totalLimit = auth.getTotalCountMap().get(uri); + Long totalApiVisitCount; + if (totalLimit != null && totalLimit > 0) { + totalApiVisitCount = apiVisitCountService.findApiVisitTotalCount(auth.getUserId(), uri, serviceCode); + if (totalApiVisitCount >= totalLimit) { + return true; + } + } + } + if (hasSubService(uri) && StringUtils.isNotBlank(serviceCode)) { + Integer totalLimit = auth.getTotalCountMap().get(uri + SUB_SERVICE_SEPARATOR + serviceCode); + if (totalLimit != null && totalLimit > 0) { + Long totalApiVisitCount = apiVisitCountService.findApiVisitTotalCount(auth.getUserId(), uri, serviceCode); + if (totalApiVisitCount >= totalLimit) { + return true; + } + } + + } + return false; + } + + private boolean isReach90SumLimit(ApiUserAuthority auth, String uri, String serviceCode) { + + if (auth == null || auth.getTotalCountMap() == null) { + return false; + } + + if (auth.getTotalCountMap() != null && auth.getTotalCountMap().get(uri) != null) { + Integer totalLimit = auth.getTotalCountMap().get(uri); + Long totalApiVisitCount; + if (totalLimit != null && totalLimit > 0) { + totalApiVisitCount = apiVisitCountService.findApiVisitTotalCount(auth.getUserId(), uri, serviceCode); + if (totalApiVisitCount.intValue() == (int) (totalLimit * 0.9)) { + return true; + } + } + } + if (hasSubService(uri) && StringUtils.isNotBlank(serviceCode)) { + Integer totalLimit = auth.getTotalCountMap().get(uri + SUB_SERVICE_SEPARATOR + serviceCode); + if (totalLimit != null && totalLimit > 0) { + Long totalApiVisitCount = apiVisitCountService.findApiVisitTotalCount(auth.getUserId(), uri, serviceCode); + if (totalApiVisitCount.intValue() == (int) (totalLimit * 0.9)) { + return true; + } + } + + } + return false; + } + + private Authority getAuthority(ActionInvocation invocation) { + Authority authority; + // »ñÈ¡·½·¨ÉϵÄȨÏÞ×¢½â + authority = invocation.getAction().getActionMethod().getAnnotation(Authority.class); + if (null != authority) { + return authority; + } + // »ñÈ¡ÀàÉϵÄȨÏÞ×¢½â + authority = invocation.getControllerInstance().getClass().getAnnotation(Authority.class); + return authority; + } + + + /** + * ¼ìÑéÊÇ·ñÓзÃÎʸÃActionµÄȨÏÞ + * + * @param tokenStr + * @param request + * @return + * @throws Exception */ - private boolean hasSubService(String uri){ - return HAS_SUB_SERVICE_URIS.contains(uri); - } + private HttpCode authorized(String tokenStr, HttpServletRequest request) throws Exception { - /** - * 2016Äê06ÔÂ06ÈÕÒÔǰµÄÓû§ÊÇÀÏÓû§£¬token²»¹ýÆÚ - * @param apiUser - * @return - */ - private boolean isOldUser(ApiUser apiUser){ - return OLD_USER_SPLITTED_DATE.after(apiUser.getCreationDate()); - } + // ¼ì²éÊÇ·ñΪapiÓû§ + HttpCode ret = new HttpCode(OpenHttpCodeEnum.AUTH_FAILD); + Token token = FangjiaApiUtil.parse2Token(tokenStr); + ApiUser apiUser = parseApiUserByToken(token); + if (null == apiUser) { + return ret; + } + if (apiUser.getDeadTime() != null && DateUtil.truncateDay(new Date()).after(apiUser.getDeadTime())) { + return new HttpCode(OpenHttpCodeEnum.USER_EXPIRED); + } + if (!isOldUser(apiUser) && isExpired(token)) { + return new HttpCode(OpenHttpCodeEnum.TOKEN_EXPIRED); + } + if (1 == apiUser.getStatus()) { + return new HttpCode(OpenHttpCodeEnum.AUTH_FAILD, "ÄãµÄÕË»§ÒÑʧЧ"); + } + if (StringUtils.isNotBlank(apiUser.getIp())) { + String ip = AnalyticsUtil.getIpAddress(request); + if (!isAuthIp(ip, apiUser)) { + ret = new HttpCode(OpenHttpCodeEnum.AUTH_FAILD, "ip[" + ip + "]ÎÞȨÏÞ·ÃÎÊAPI"); + return ret; + } + } - /** - * ÅжÏTokenÊÇ·ñ¹ýÆÚ - * @param token - * @return - */ - private boolean isExpired(Token token){ - return System.currentTimeMillis() / 1000 - token.getTimestamp() > TOKEN_EXPIRED_TIME; - } + String uri = request.getRequestURI(); + ApiUserAuthority auth = this.apiUserAuthorityService.findByUserId(apiUser.getId()); + User user = apiUserService.findUserById(apiUser.getId()); + if (auth != null) { + AuthenticationBean.get(request, apiUser, user, auth); + } + uri = OpenConfig.getConfig().isDevelopmentEnvironment() ? uri.replace("/fangjia-open", "") : uri; + // ¼ì²éÊÇ·ñÓзÃÎʸÃActionµÄȨÏÞ + boolean authAction = null != auth && auth.getOpenResourseUris().contains(uri); + String cityName = request.getParameter("city"); + if (StringUtils.isBlank(cityName)) { + cityName = request.getParameter("cityName"); + } + if (StringUtils.isNotBlank(cityName)) { + boolean authCity = StringUtils.isNotBlank(apiUser.getCity()) && !StringUtils.equalsIgnoreCase(apiUser.getCity(), "all"); + if (authCity) { + cityName = request.getParameter("city"); + cityName = RegionData.formatCity(cityName); + if (!RegionData.isCity(cityName)) { + ret = new HttpCode(OpenHttpCodeEnum.ARGUMENT_INVALID); + ret.setErrorMessage("³ÇÊзǷ¨"); + return ret; + } + } + } + boolean authCity = isAuthCity(cityName, apiUser); + if (!authCity) { + ret = new HttpCode(OpenHttpCodeEnum.AUTH_FAILD, "Äúδ¿ªÍ¨³ÇÊÐ" + (StringUtils.isNotBlank(cityName) ? cityName : StringUtils.EMPTY) + "µÄȨÏÞ"); + } + if (authAction && authCity) { + if (hasSubService(uri)) { + List serviceCodes = getServiceCode(request); + for (String serviceCode : serviceCodes) { + if (!auth.getOpenResourseUris().contains(uri + SUB_SERVICE_SEPARATOR + serviceCode)) { + ret = new HttpCode(OpenHttpCodeEnum.AUTH_FAILD, "ÎÞȨÏÞ·ÃÎÊ·þÎñ:" + serviceCode); + return ret; + } + if (isReachDeadline(auth, uri, serviceCode)) { + ret = new HttpCode(OpenHttpCodeEnum.SERVICE_EXPIRED, serviceCode + "·þÎñÒѹýÆÚ"); + return ret; + } + if (isReachUpperLimit(auth, uri, serviceCode)) { + ret = new HttpCode(OpenHttpCodeEnum.UPPER_LIMIT, serviceCode + "½ñÈÕÒÑ´ïµ½Åä¶îÉÏÏÞ"); + return ret; + } + // ¼ì²âÊÇ·ñ´ïµ½×ÜÊý·ÃÎÊÉÏÏÞ + if (isReachSumLimit(auth, uri, serviceCode)) { + ret = new HttpCode(OpenHttpCodeEnum.UPPER_LIMIT, serviceCode + "ÒÑ´ïµ½Åä¶îÉÏÏÞ"); + return ret; + } + // ¼ì²âÊÇ·ñ´ïµ½×ÜÊýµÄ90% + if (isReach90SumLimit(auth, uri, serviceCode)) { + kafkaProducerUtils.send(SMS_DATA_TOPIC, SMS_DATA_TOPIC_PROFIX + apiUser.getPhone() + "-" + user.getUserName() + "-" + uri); + } + } - /** - * - * @param ip ÑéÖ¤¿Í»§IPÊÇ·ñÔÚ×¢²áµÄ°×Ãûµ¥ÖÐ - * @param apiUser - * @return - */ - private boolean isAuthIp(String ip,ApiUser apiUser){ - if(StringUtils.isBlank(ip) || StringUtils.isBlank(apiUser.getIp())){ - return false; - } - String[] ips = apiUser.getIp().split("\n"); - for(String authIp:ips){ - if(StringUtils.isNotBlank(authIp) && ip.startsWith(authIp.replaceAll("\\s", ""))){ - return true; - } - } - return false; - } + } else { + if (isReachDeadline(auth, uri, null)) { + ret = new HttpCode(OpenHttpCodeEnum.UPPER_LIMIT, "·þÎñÒѹýÆÚ"); + return ret; + } + // ¼ì²âÊÇ·ñ´ïµ½½ñÌì·ÃÎÊÉÏÏÞ + if (isReachUpperLimit(auth, uri, null)) { + ret = new HttpCode(OpenHttpCodeEnum.UPPER_LIMIT, "½ñÈÕÒÑ´ïµ½Åä¶îÉÏÏÞ"); + return ret; + } + // ¼ì²âÊÇ·ñ´ïµ½×ÜÊý·ÃÎÊÉÏÏÞ + if (isReachSumLimit(auth, uri, null)) { + ret = new HttpCode(OpenHttpCodeEnum.UPPER_LIMIT, "ÒÑ´ïµ½Åä¶îÉÏÏÞ"); + return ret; + } + // ¼ì²âÊÇ·ñ´ïµ½×ÜÊýµÄ90% + if (isReach90SumLimit(auth, uri, null)) { + kafkaProducerUtils.send(SMS_DATA_TOPIC, SMS_DATA_TOPIC_PROFIX + apiUser.getPhone() + "-" + user.getUserName() + "-" + uri); + } + } + return null; + } - /** - * ÊÇ·ñÓÐȨÏÞ·ÃÎʸóÇÊÐ - * - * @param cityName - * @param apiUser - * @return - */ - private boolean isAuthCity(String cityName, ApiUser apiUser) { - // Èô·ÃÎʵ±Ç°½Ó¿Ú²»ÐèÒª³ÇÊвÎÊý£¬Ôò·µ»Øtrue - if (StringUtils.isBlank(cityName)) { - return true; - } - if(!RegionData.isCity(cityName)){ - String city = RegionData.formatCity(cityName); - if(null != city){ - cityName = city; - } - } - // Èôµ±Ç°½Ó¿ÚÐèÒª³ÇÊÐ,¼ì²éÊÇ·ñÓзÃÎʵ±Ç°³ÇÊеÄȨÏÞ - boolean authCity = StringUtils.isNotBlank(apiUser.getCity()) && !StringUtils.equalsIgnoreCase(apiUser.getCity(), "all"); - if (authCity) { - ServerArea city = ServerAreaData.getServerAreaByDisplayDefaultNull(cityName); - if (null != city) { - return apiUser.getCity().contains(city.getSpell()); - } - } - return true; - } - - private ApiUser parseApiUserByToken(Token token){ - - if(token == null){ - return null; - } - ApiUser apiUser = apiUserService.findApiUserById(token.getUserId()); - if(apiUser == null){ - return null; - } - if(!apiUser.getAppKey().equals(token.getAppKey())){ - return null; - } - return apiUser; - } + return ret; + } - /** - * аætokenÑéÖ¤ - * - * @param token - * @return - */ - private ApiUser checkNewAuthorized(String token) { + /** + * @param request + * @return + */ + private List getServiceCode(HttpServletRequest request) { - Map tokenMap = FangjiaApiUtil.parseToken(token); - if (tokenMap == null) { - return null; - } - // tokenÑéÖ¤ºó£¬ÄÃÈ¡³öµÄ×Ö¶ÎÔÙÈ¥Êý¾Ý¿âÑéÖ¤Ò»±é - if (StringUtils.isNotBlank(tokenMap.get("userid")) && !"null".equals(tokenMap.get("userid"))) { - ApiUser apiUser = apiUserService.findApiUserById(Long.parseLong(tokenMap.get("userid"))); - if (apiUser != null) { - if (tokenMap.get("appKey").equals(apiUser.getAppKey())) { - return apiUser; - } - } - } - return null; - } + String serviceCode = request.getParameter(SERVICE_CODE_PARAM_NAME); + if (StringUtils.isBlank(serviceCode)) { + return Collections.emptyList(); + } + return Arrays.asList(serviceCode.split(",|£¬")); + } + + /** + * ÅжϸÃAPIÊÇ·ñÓµÓÐ×ÓȨÏÞ + * + * @param uri + * @return + */ + private boolean hasSubService(String uri) { + return HAS_SUB_SERVICE_URIS.contains(uri); + } + + /** + * 2016Äê06ÔÂ06ÈÕÒÔǰµÄÓû§ÊÇÀÏÓû§£¬token²»¹ýÆÚ + * + * @param apiUser + * @return + */ + private boolean isOldUser(ApiUser apiUser) { + return OLD_USER_SPLITTED_DATE.after(apiUser.getCreationDate()); + } + + /** + * ÅжÏTokenÊÇ·ñ¹ýÆÚ + * + * @param token + * @return + */ + private boolean isExpired(Token token) { + return System.currentTimeMillis() / 1000 - token.getTimestamp() > TOKEN_EXPIRED_TIME; + } + + /** + * @param ip ÑéÖ¤¿Í»§IPÊÇ·ñÔÚ×¢²áµÄ°×Ãûµ¥ÖÐ + * @param apiUser + * @return + */ + private boolean isAuthIp(String ip, ApiUser apiUser) { + if (StringUtils.isBlank(ip) || StringUtils.isBlank(apiUser.getIp())) { + return false; + } + String[] ips = apiUser.getIp().split("\n"); + for (String authIp : ips) { + if (StringUtils.isNotBlank(authIp) && ip.startsWith(authIp.replaceAll("\\s", ""))) { + return true; + } + } + return false; + } + + /** + * ÊÇ·ñÓÐȨÏÞ·ÃÎʸóÇÊÐ + * + * @param cityName + * @param apiUser + * @return + */ + private boolean isAuthCity(String cityName, ApiUser apiUser) { + // Èô·ÃÎʵ±Ç°½Ó¿Ú²»ÐèÒª³ÇÊвÎÊý£¬Ôò·µ»Øtrue + if (StringUtils.isBlank(cityName)) { + return true; + } + if (!RegionData.isCity(cityName)) { + String city = RegionData.formatCity(cityName); + if (null != city) { + cityName = city; + } + } + // Èôµ±Ç°½Ó¿ÚÐèÒª³ÇÊÐ,¼ì²éÊÇ·ñÓзÃÎʵ±Ç°³ÇÊеÄȨÏÞ + boolean authCity = StringUtils.isNotBlank(apiUser.getCity()) && !StringUtils.equalsIgnoreCase(apiUser.getCity(), "all"); + if (authCity) { + ServerArea city = ServerAreaData.getServerAreaByDisplayDefaultNull(cityName); + if (null != city) { + return apiUser.getCity().contains(city.getSpell()); + } + } + return true; + } + + private ApiUser parseApiUserByToken(Token token) { + + if (token == null) { + return null; + } + ApiUser apiUser = apiUserService.findApiUserById(token.getUserId()); + if (apiUser == null) { + return null; + } + if (!apiUser.getAppKey().equals(token.getAppKey())) { + return null; + } + return apiUser; + } - public void setApiUserService(ApiUserService apiUserService) { - this.apiUserService = apiUserService; - } + /** + * аætokenÑéÖ¤ + * + * @param token + * @return + */ + private ApiUser checkNewAuthorized(String token) { - public void setApiUserAuthorityService(ApiUserAuthorityService apiUserAuthorityService) { - this.apiUserAuthorityService = apiUserAuthorityService; - } + Map tokenMap = FangjiaApiUtil.parseToken(token); + if (tokenMap == null) { + return null; + } + // tokenÑéÖ¤ºó£¬ÄÃÈ¡³öµÄ×Ö¶ÎÔÙÈ¥Êý¾Ý¿âÑéÖ¤Ò»±é + if (StringUtils.isNotBlank(tokenMap.get("userid")) && !"null".equals(tokenMap.get("userid"))) { + ApiUser apiUser = apiUserService.findApiUserById(Long.parseLong(tokenMap.get("userid"))); + if (apiUser != null) { + if (tokenMap.get("appKey").equals(apiUser.getAppKey())) { + return apiUser; + } + } + } + return null; + } - public void setApiVisitCountService(ApiVisitCountService apiVisitCountService) { - this.apiVisitCountService = apiVisitCountService; - } + public void setApiUserService(ApiUserService apiUserService) { + this.apiUserService = apiUserService; + } + + public void setApiUserAuthorityService(ApiUserAuthorityService apiUserAuthorityService) { + this.apiUserAuthorityService = apiUserAuthorityService; + } + + public void setApiVisitCountService(ApiVisitCountService apiVisitCountService) { + this.apiVisitCountService = apiVisitCountService; + } + + public void setKafkaProducerUtils(KafkaProducerUtils kafkaProducerUtils) { + this.kafkaProducerUtils = kafkaProducerUtils; + } } diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/model/AddesssMatchModel.java b/projects/fangjia-open/src/main/java/com/fangjia/open/model/AddesssMatchModel.java index 1a8907341..6feef4517 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/model/AddesssMatchModel.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/model/AddesssMatchModel.java @@ -22,6 +22,7 @@ public class AddesssMatchModel extends FangjiaApiModel { private boolean useMap; private String address_1; private String address_2; + private String propertyType; private String showCode; @@ -153,4 +154,12 @@ public class AddesssMatchModel extends FangjiaApiModel { public void setShowCode(String showCode) { this.showCode = showCode; } + + public String getPropertyType() { + return propertyType; + } + + public void setPropertyType(String propertyType) { + this.propertyType = propertyType; + } } diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/model/ApiUserModel.java b/projects/fangjia-open/src/main/java/com/fangjia/open/model/ApiUserModel.java index 22540ffea..a3c228c25 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/model/ApiUserModel.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/model/ApiUserModel.java @@ -1,6 +1,12 @@ package com.fangjia.open.model; +import com.fangjia.dal.mongo.model.ApiInvokeStatistical; +import com.fangjia.dal.mongo.open.model.ApiUserAuthority; +import com.fangjia.service.open.*; + import java.util.Date; +import java.util.List; +import java.util.Map; /** * APIÓû§¹ÜÀíModel @@ -12,6 +18,620 @@ public class ApiUserModel extends FangjiaApiModel{ private Date endDate; private String uri; + private static final long serialVersionUID = 7044341510628330454L; + + private String begDateStr;// ²éѯ¿ªÊ¼ÈÕÆÚ + private String endDateStr;// ²éѯ½áÊøÈÕÆÚ + private String statDate; + private String appKey; + private String userName; + private String displayName; + private String siteName; + private String password; + private String email; + private String ip; + private Integer isTest; + private Integer purpose; + private String msg; + private Long userId; + private String company; + private List apiUserBoList; + private List eachCityBoList; + private String limitCountMap; + private String totalCountMap; + private Integer creditLevelStatus; + private String priceType; + private Map priceRatingMap; + private Integer isMonitor; + + private String contact; + + private String phone; + + public String getPriceType() { + return priceType; + } + + public void setPriceType(String priceType) { + this.priceType = priceType; + } + + public List getEachCityBoList() { + return eachCityBoList; + } + + public void setEachCityBoList(List eachCityBoList) { + this.eachCityBoList = eachCityBoList; + } + + private Integer sum; + private Integer limit; + /*** ȨÏÞ¿ØÖÆÏà¹Ø **/ + private ApiUserBo apiUserBo; + private List authorityList; + private ApiUserAuthority authority; + private List authorityBoList; + //private List serverAreaList; + private List> serverAreaList; + private String openCitys;// ºº×Ö˵Ã÷ + private List cityFirstLetters;// ³ÇÊÐÆ´ÒôÊ××Öĸ + private String type; + private String citys;// spell + private String unCheckCitys;// Ò³Ãæ·´Ñ¡µÄcity + private Integer status; + private boolean hasAuth; + private boolean supportLatLng; + private Integer maxFrequency; + private String frequencyPeriod; + private Integer maximum; + + private ApiInvokeStatistical apiInvokeStatistical; + private Double one; + private Double newOne; + private Double two; + private Double three; + private Double four; + private Double five; + private Date deadTime; + private String manager; + private Double evaluateRate; + + private String data; + + private Integer isCheckCount; + + private String openResourseUrisMap; + + public String getOpenResourseUrisMap() { + return openResourseUrisMap; + } + + public void setOpenResourseUrisMap(String openResourseUrisMap) { + this.openResourseUrisMap = openResourseUrisMap; + } + + public Integer getIsCheckCount() { + return isCheckCount; + } + + public void setIsCheckCount(Integer isCheckCount) { + this.isCheckCount = isCheckCount; + } + + public String getData() { + return data; + } + + public void setData(String data) { + this.data = data; + } + + public String getDisplayName() { + return displayName; + } + + private String chartSeries; + + private List OpenUriAnalyBoList; + private List statAnalyBoList; + private Integer way; + private Map resourceMap; + private String query; + private Integer totalCount; + private String xAxis; + private String credits; + private String uncitys; + + public String getUncitys() { + return uncitys; + } + + public void setUncitys(String uncitys) { + this.uncitys = uncitys; + } + + public String getCredits() { + return credits; + } + + public void setCredits(String credits) { + this.credits = credits; + } + + public String getxAxis() { + return xAxis; + } + + public void setxAxis(String xAxis) { + this.xAxis = xAxis; + } + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + + public String getSiteName() { + return siteName; + } + + public void setSiteName(String siteName) { + this.siteName = siteName; + } + + public String getAppKey() { + return appKey; + } + + public void setAppKey(String appKey) { + this.appKey = appKey; + } + + public String getBegDateStr() { + return begDateStr; + } + + public void setBegDateStr(String begDateStr) { + this.begDateStr = begDateStr; + } + + public String getEndDateStr() { + return endDateStr; + } + + public void setEndDateStr(String endDateStr) { + this.endDateStr = endDateStr; + } + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public List getApiUserBoList() { + return apiUserBoList; + } + + public void setApiUserBoList(List apiUserBoList) { + this.apiUserBoList = apiUserBoList; + } + + public ApiUserBo getApiUserBo() { + return apiUserBo; + } + + public void setApiUserBo(ApiUserBo apiUserBo) { + this.apiUserBo = apiUserBo; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } + + public String getIp() { + return ip; + } + + public void setIp(String ip) { + this.ip = ip; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public List getAuthorityList() { + return authorityList; + } + + public void setAuthorityList(List authorityList) { + this.authorityList = authorityList; + } + + public ApiUserAuthority getAuthority() { + return authority; + } + + public void setAuthority(ApiUserAuthority authority) { + this.authority = authority; + } + + + public boolean isHasAuth() { + return hasAuth; + } + + public void setHasAuth(boolean hasAuth) { + this.hasAuth = hasAuth; + } + + public boolean isSupportLatLng() { + return supportLatLng; + } + + public void setSupportLatLng(boolean supportLatLng) { + this.supportLatLng = supportLatLng; + } + + public List getAuthorityBoList() { + return authorityBoList; + } + + public void setAuthorityBoList(List authorityBoList) { + this.authorityBoList = authorityBoList; + } + + public List getCityFirstLetters() { + return cityFirstLetters; + } + + public void setCityFirstLetters(List cityFirstLetters) { + this.cityFirstLetters = cityFirstLetters; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + /*public List getServerAreaList() { + return serverAreaList; + } + + public void setServerAreaList(List serverAreaList) { + this.serverAreaList = serverAreaList; + }*/ + public List> getServerAreaList() { + return serverAreaList; + } + + public void setServerAreaList(List> serverAreaList) { + this.serverAreaList = serverAreaList; + } + + public String getCitys() { + return citys; + } + + public void setCitys(String citys) { + this.citys = citys; + } + + public String getOpenCitys() { + return openCitys; + } + + public void setOpenCitys(String openCitys) { + this.openCitys = openCitys; + } + + public String getUnCheckCitys() { + return unCheckCitys; + } + + public void setUnCheckCitys(String unCheckCitys) { + this.unCheckCitys = unCheckCitys; + } + + public Integer getSum() { + return sum; + } + + public void setSum(Integer sum) { + this.sum = sum; + } + + + public Integer getLimit() { + return limit; + } + + public void setLimit(Integer limit) { + this.limit = limit; + } + + public Integer getStatus() { + return status; + } + + public void setStatus(Integer status) { + this.status = status; + } + + public String getCompany() { + return company; + } + + public void setCompany(String company) { + this.company = company; + } + + public Integer getMaximum() { + return maximum; + } + + public void setMaximum(Integer maximum) { + this.maximum = maximum; + } + + public String getFrequencyPeriod() { + return frequencyPeriod; + } + + public void setFrequencyPeriod(String frequencyPeriod) { + this.frequencyPeriod = frequencyPeriod; + } + + public Integer getMaxFrequency() { + return maxFrequency; + } + + public void setMaxFrequency(Integer maxFrequency) { + this.maxFrequency = maxFrequency; + } + public List getOpenUriAnalyBoList() { + return OpenUriAnalyBoList; + } + + public void setOpenUriAnalyBoList(List openUriAnalyBoList) { + OpenUriAnalyBoList = openUriAnalyBoList; + } + + public String getChartSeries() { + return chartSeries; + } + + public void setChartSeries(String chartSeries) { + this.chartSeries = chartSeries; + } + + public String getStatDate() { + return statDate; + } + + public void setStatDate(String statDate) { + this.statDate = statDate; + } + + public Integer getWay() { + return way; + } + + public void setWay(Integer way) { + this.way = way; + } + + public Map getResourceMap() { + return resourceMap; + } + + public void setResourceMap(Map resourceMap) { + this.resourceMap = resourceMap; + } + + public List getStatAnalyBoList() { + return statAnalyBoList; + } + + public void setStatAnalyBoList(List statAnalyBoList) { + this.statAnalyBoList = statAnalyBoList; + } + + public String getQuery() { + return query; + } + + public void setQuery(String query) { + this.query = query; + } + + public Integer getTotalCount() { + return totalCount; + } + + public void setTotalCount(Integer totalCount) { + this.totalCount = totalCount; + } + + public ApiInvokeStatistical getApiInvokeStatistical() { + return apiInvokeStatistical; + } + + public void setApiInvokeStatistical(ApiInvokeStatistical apiInvokeStatistical) { + this.apiInvokeStatistical = apiInvokeStatistical; + } + public Double getEvaluateRate() { + return evaluateRate; + } + + public void setEvaluateRate(Double evaluateRate) { + this.evaluateRate = evaluateRate; + } + + public Integer getIsTest() { + return isTest; + } + + public void setIsTest(Integer isTest) { + this.isTest = isTest; + } + + public String getLimitCountMap() { + return limitCountMap; + } + + public void setLimitCountMap(String limitCountMap) { + this.limitCountMap = limitCountMap; + } + + public String getTotalCountMap() { + return totalCountMap; + } + + public void setTotalCountMap(String totalCountMap) { + this.totalCountMap = totalCountMap; + } + + public Integer getPurpose() { + return purpose; + } + + public void setPurpose(Integer purpose) { + this.purpose = purpose; + } + + public Map getPriceRatingMap() { + return priceRatingMap; + } + + public void setPriceRatingMap(Map priceRatingMap) { + this.priceRatingMap = priceRatingMap; + } + + public Double getOne() { + return one; + } + + public void setOne(Double one) { + this.one = one; + } + + public Double getNewOne() { + return newOne; + } + + public void setNewOne(Double newOne) { + this.newOne = newOne; + } + + public Double getTwo() { + return two; + } + + public void setTwo(Double two) { + this.two = two; + } + + public Double getThree() { + return three; + } + + public void setThree(Double three) { + this.three = three; + } + + public Double getFour() { + return four; + } + + public void setFour(Double four) { + this.four = four; + } + + public Double getFive() { + return five; + } + + public void setFive(Double five) { + this.five = five; + } + + public Integer getCreditLevelStatus() { + return creditLevelStatus; + } + + public void setCreditLevelStatus(Integer creditLevelStatus) { + this.creditLevelStatus = creditLevelStatus; + } + + public Date getDeadTime() { + return deadTime; + } + + public void setDeadTime(Date deadTime) { + this.deadTime = deadTime; + } + + public String getManager() { + return manager; + } + + public void setManager(String manager) { + this.manager = manager; + } + + public Integer getIsMonitor() { + return isMonitor; + } + + public void setIsMonitor(Integer isMonitor) { + this.isMonitor = isMonitor; + } + + public String getContact() { + return contact; + } + + public void setContact(String contact) { + this.contact = contact; + } + + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + public Date getStartDate() { return startDate; } diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/model/BasicPageModel.java b/projects/fangjia-open/src/main/java/com/fangjia/open/model/BasicPageModel.java new file mode 100644 index 000000000..34512f434 --- /dev/null +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/model/BasicPageModel.java @@ -0,0 +1,115 @@ +package com.fangjia.open.model; + +import com.fangjia.open.APIConstant; +import com.fangjia.open.HttpStatusCodeEnum; +import com.thoughtworks.xstream.annotations.XStreamAlias; +import org.sothis.web.mvc.ActionContext; + +@XStreamAlias("xml") +public class BasicPageModel { + + private int code; + + private String msg; + + private Object result; + + private String tid; + + private int total; + + public BasicPageModel(int code, String msg) { + super(); + this.code = code; + this.msg = msg; + } + + public BasicPageModel(HttpStatusCodeEnum status){ + this.code = status.getCode(); + this.msg = status.getMsg(); + } + + public static BasicPageModel buildOKModel() { + BasicPageModel model = new BasicPageModel(HttpStatusCodeEnum.OK); + return model; + } + + public static BasicPageModel buildModel(int code, String msg){ + return new BasicPageModel( code, msg); + } + + public static BasicPageModel buildUnAuthorizedModel() { + BasicPageModel model = new BasicPageModel(HttpStatusCodeEnum.UN_AUTHORIZED); + return model; + } + + public static BasicPageModel buildBadRequestModel(String msg){ + BasicPageModel model = new BasicPageModel(HttpStatusCodeEnum.BAD_REQUEST); + model.setMsg(msg); + return model; + } + + public static BasicPageModel buildForbidModel(String msg){ + BasicPageModel model = new BasicPageModel(HttpStatusCodeEnum.SERVER_FORBID); + model.setMsg(msg); + return model; + } + + + public static BasicPageModel buildServerErrorModel(){ + BasicPageModel model = new BasicPageModel(HttpStatusCodeEnum.SERVER_ERROR); + return model; + } + + public static void markNoDataRequest(){ + ActionContext.getContext().set(APIConstant.IS_RETURN_DATA, Boolean.FALSE); + } + + public BasicPageModel markNoData(){ + markNoDataRequest(); + return this; + } + + public int getCode() { + return code; + } + + public BasicPageModel setCode(int code) { + this.code = code; + return this; + } + + public String getMsg() { + return msg; + } + + public BasicPageModel setMsg(String msg) { + this.msg = msg; + return this; + } + + public Object getResult() { + return result; + } + + public BasicPageModel setResult(Object result) { + this.result = result; + return this; + } + + public void setTid(String tid) { + this.tid = tid; + } + + public String getTid() { + return tid; + } + + public int getTotal() { + return total; + } + + public void setTotal(int total) { + this.total = total; + } +} diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/model/CommunitySummaryRequestDto.java b/projects/fangjia-open/src/main/java/com/fangjia/open/model/CommunitySummaryRequestDto.java index c5af8f307..fb5ed4f7b 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/model/CommunitySummaryRequestDto.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/model/CommunitySummaryRequestDto.java @@ -9,6 +9,11 @@ package com.fangjia.open.model; */ public class CommunitySummaryRequestDto extends FangjiaApiModel { + /** + * Ð¡ÇøID + */ + private String id; + /** * ³ÇÊÐ */ @@ -86,4 +91,12 @@ public class CommunitySummaryRequestDto extends FangjiaApiModel { public void setMemo(String memo) { this.memo = memo; } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } } diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/model/DistrictFacilitysModel.java b/projects/fangjia-open/src/main/java/com/fangjia/open/model/DistrictFacilitysModel.java new file mode 100644 index 000000000..ca5c12046 --- /dev/null +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/model/DistrictFacilitysModel.java @@ -0,0 +1,344 @@ +package com.fangjia.open.model; + +import java.util.Date; +import java.util.List; + +/** + * Ð¡ÇøÖܱßÅäÌ× + */ +public class DistrictFacilitysModel { + private static final long serialVersionUID = -9200383212669643823L; + private String id; + private String city; + private String region; + private String districtName; + private List kindergarten; + private List primarySchool; + private List middleSchool; + private List university; + private List hospital; + private List shop; + private List supermarket; + private List foodShop; + private List bus; + private List metro; + private List bank; + private List atm; + private String innerFacilities; + private String carSite; + private String carSiteDes; + + private Double trafficScore; + private Double hospitalScore; + private Double shopScore; + private Double schoolScore; + private Double bankScore; + + private Date creationDate; + + private List positives; // ÕýÃæ + private List negatives; // ¸ºÃæ + private List appraisalNegative; // ¸ºÃæ + private List appraisalPositive; // ÕýÃæ + + /** + * 标签得分 + */ + private Double traScore; + private Double virScore; + private Double aroScore; + private Double tradScore; + + private String imgUrl3D; + + private List school; + private List keySchool; + + public String getCity() { + return city; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public void setCity(String city) { + this.city = city; + } + + public String getRegion() { + return region; + } + + public void setRegion(String region) { + this.region = region; + } + + public String getDistrictName() { + return districtName; + } + + public void setDistrictName(String districtName) { + this.districtName = districtName; + } + + public List getKindergarten() { + return kindergarten; + } + + public void setKindergarten(List kindergarten) { + this.kindergarten = kindergarten; + } + + public List getPrimarySchool() { + return primarySchool; + } + + public void setPrimarySchool(List primarySchool) { + this.primarySchool = primarySchool; + } + + public List getMiddleSchool() { + return middleSchool; + } + + public void setMiddleSchool(List middleSchool) { + this.middleSchool = middleSchool; + } + + public List getUniversity() { + return university; + } + + public void setUniversity(List university) { + this.university = university; + } + + public List getHospital() { + return hospital; + } + + public void setHospital(List hospital) { + this.hospital = hospital; + } + + public List getShop() { + return shop; + } + + public void setShop(List shop) { + this.shop = shop; + } + + public List getSupermarket() { + return supermarket; + } + + public void setSupermarket(List supermarket) { + this.supermarket = supermarket; + } + + public List getFoodShop() { + return foodShop; + } + + public void setFoodShop(List foodShop) { + this.foodShop = foodShop; + } + + public List getBus() { + return bus; + } + + public void setBus(List bus) { + this.bus = bus; + } + + public List getMetro() { + return metro; + } + + public void setMetro(List metro) { + this.metro = metro; + } + + public List getBank() { + return bank; + } + + public void setBank(List bank) { + this.bank = bank; + } + + public List getAtm() { + return atm; + } + + public void setAtm(List atm) { + this.atm = atm; + } + + public String getInnerFacilities() { + return innerFacilities; + } + + public void setInnerFacilities(String innerFacilities) { + this.innerFacilities = innerFacilities; + } + + public String getCarSite() { + return carSite; + } + + public void setCarSite(String carSite) { + this.carSite = carSite; + } + + public String getCarSiteDes() { + return carSiteDes; + } + + public void setCarSiteDes(String carSiteDes) { + this.carSiteDes = carSiteDes; + } + + public Double getTrafficScore() { + return trafficScore; + } + + public void setTrafficScore(Double trafficScore) { + this.trafficScore = trafficScore; + } + + public Double getHospitalScore() { + return hospitalScore; + } + + public void setHospitalScore(Double hospitalScore) { + this.hospitalScore = hospitalScore; + } + + public Double getShopScore() { + return shopScore; + } + + public void setShopScore(Double shopScore) { + this.shopScore = shopScore; + } + + public Double getSchoolScore() { + return schoolScore; + } + + public void setSchoolScore(Double schoolScore) { + this.schoolScore = schoolScore; + } + + public Double getBankScore() { + return bankScore; + } + + public void setBankScore(Double bankScore) { + this.bankScore = bankScore; + } + + public Date getCreationDate() { + return creationDate; + } + + public void setCreationDate(Date creationDate) { + this.creationDate = creationDate; + } + + public List getPositives() { + return positives; + } + + public void setPositives(List positives) { + this.positives = positives; + } + + public List getNegatives() { + return negatives; + } + + public void setNegatives(List negatives) { + this.negatives = negatives; + } + + public List getAppraisalNegative() { + return appraisalNegative; + } + + public void setAppraisalNegative(List appraisalNegative) { + this.appraisalNegative = appraisalNegative; + } + + public List getAppraisalPositive() { + return appraisalPositive; + } + + public void setAppraisalPositive(List appraisalPositive) { + this.appraisalPositive = appraisalPositive; + } + + public Double getTraScore() { + return traScore; + } + + public void setTraScore(Double traScore) { + this.traScore = traScore; + } + + public Double getVirScore() { + return virScore; + } + + public void setVirScore(Double virScore) { + this.virScore = virScore; + } + + public Double getAroScore() { + return aroScore; + } + + public void setAroScore(Double aroScore) { + this.aroScore = aroScore; + } + + public Double getTradScore() { + return tradScore; + } + + public void setTradScore(Double tradScore) { + this.tradScore = tradScore; + } + + public String getImgUrl3D() { + return imgUrl3D; + } + + public void setImgUrl3D(String imgUrl3D) { + this.imgUrl3D = imgUrl3D; + } + + public List getSchool() { + return school; + } + + public void setSchool(List school) { + this.school = school; + } + + public List getKeySchool() { + return keySchool; + } + + public void setKeySchool(List keySchool) { + this.keySchool = keySchool; + } +} diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/model/HouseSearchModel.java b/projects/fangjia-open/src/main/java/com/fangjia/open/model/HouseSearchModel.java index 63a85c4b3..39fefbbdc 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/model/HouseSearchModel.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/model/HouseSearchModel.java @@ -13,6 +13,22 @@ public class HouseSearchModel extends SearchModel { private String unitNo; private Double size; private Boolean showDetail; + + private String city; + + private String location; + + private String locationType; + + private String propertyType; + + private String houseType; + + private String district; + + private String cat; + + private Integer pageSize; @Override public QueryBean getQueryBean() { HouseQueryBean queryBean = new HouseQueryBean(); @@ -125,4 +141,72 @@ public class HouseSearchModel extends SearchModel { public void setId(String id) { this.id = id; } + + @Override + public String getCity() { + return city; + } + + @Override + public void setCity(String city) { + this.city = city; + } + + public String getLocation() { + return location; + } + + public void setLocation(String location) { + this.location = location; + } + + public String getLocationType() { + return locationType; + } + + public void setLocationType(String locationType) { + this.locationType = locationType; + } + + public String getPropertyType() { + return propertyType; + } + + public void setPropertyType(String propertyType) { + this.propertyType = propertyType; + } + + public String getHouseType() { + return houseType; + } + + public void setHouseType(String houseType) { + this.houseType = houseType; + } + + public String getDistrict() { + return district; + } + + public void setDistrict(String district) { + this.district = district; + } + + public String getCat() { + return cat; + } + + public void setCat(String cat) { + this.cat = cat; + } + + @Override + public Integer getPageSize() { + return pageSize; + } + + @Override + public void setPageSize(Integer pageSize) { + this.pageSize = pageSize; + } } diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/model/StatsIndexModel.java b/projects/fangjia-open/src/main/java/com/fangjia/open/model/StatsIndexModel.java index ec0d88a5a..305d4f6fe 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/model/StatsIndexModel.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/model/StatsIndexModel.java @@ -10,8 +10,11 @@ public class StatsIndexModel { private String id; private String city; - - private String yearmonth; + private String district; + private String name; + private String type; + + private Integer yearmonth; private Integer source; @@ -65,11 +68,11 @@ public class StatsIndexModel { this.city = city; } - public String getYearmonth() { + public Integer getYearmonth() { return yearmonth; } - public void setYearmonth(String yearmonth) { + public void setYearmonth(Integer yearmonth) { this.yearmonth = yearmonth; } @@ -216,7 +219,28 @@ public class StatsIndexModel { public void setIfNew(Integer ifNew) { this.ifNew = ifNew; } - - - + + public String getDistrict() { + return district; + } + + public void setDistrict(String district) { + this.district = district; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } } diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/model/weixin/DistrictModel.java b/projects/fangjia-open/src/main/java/com/fangjia/open/model/weixin/DistrictModel.java index 5f9c5a223..b3c210301 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/model/weixin/DistrictModel.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/model/weixin/DistrictModel.java @@ -57,6 +57,15 @@ public class DistrictModel extends BaseModel { * ÅжÏÊDz»ÊÇÓÑ´ï */ private boolean isYouDa; + //ÓÃÓÚɾ³ýºÍÐÂÔö + // ͼƬurl + private String url; + //·¿ÐÍͼ »ò Í⾰ͼ + private String PicType; + //¼¸ÊÒ + private String roomType; + + private List imageUrls; public Boolean getShowPrice() { return showPrice; @@ -241,4 +250,35 @@ public class DistrictModel extends BaseModel { // public void setBuildName(String buildName) { // this.buildName = buildName; // } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getRoomType() { + return roomType; + } + public void setRoomType(String roomType) { + this.roomType = roomType; + } + + public String getPicType() { + return PicType; + } + + public void setPicType(String picType) { + PicType = picType; + } + + public List getImageUrls() { + return imageUrls; + } + + public void setImageUrls(List imageUrls) { + this.imageUrls = imageUrls; + } } diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/model/weixin/EvaluationModel.java b/projects/fangjia-open/src/main/java/com/fangjia/open/model/weixin/EvaluationModel.java index cdf645a31..44cc2ca36 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/model/weixin/EvaluationModel.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/model/weixin/EvaluationModel.java @@ -57,6 +57,9 @@ public class EvaluationModel extends BaseModel{ private Map> reportFileMap; private UserTrades userTrades; private String address; + private Integer buildType; + private String name; + private String region; public void setId(String id) { @@ -326,4 +329,28 @@ public class EvaluationModel extends BaseModel{ public void setLoan(Integer loan) { this.loan = loan; } + + public Integer getBuildType() { + return buildType; + } + + public void setBuildType(Integer buildType) { + this.buildType = buildType; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getRegion() { + return region; + } + + public void setRegion(String region) { + this.region = region; + } } diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/model/weixin/UserModel.java b/projects/fangjia-open/src/main/java/com/fangjia/open/model/weixin/UserModel.java index 400112bfb..88d8fb971 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/model/weixin/UserModel.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/model/weixin/UserModel.java @@ -22,6 +22,11 @@ public class UserModel extends BaseModel { private String appId;//²âÊÔ private String appSecret;//²âÊÔ private String sid;//²âÊÔ + + /** + * µÇ¼À´Ô´£ºAI¹À¼ÛС³ÌÐò + */ + private String source; public List getCitys() { return citys; @@ -126,4 +131,12 @@ public class UserModel extends BaseModel { public void setPass2(String pass2) { this.pass2 = pass2; } + + public String getSource() { + return source; + } + + public void setSource(String source) { + this.source = source; + } } diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/util/FileDao.java b/projects/fangjia-open/src/main/java/com/fangjia/open/util/FileDao.java index 2919c8a6c..be6fa3e75 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/util/FileDao.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/util/FileDao.java @@ -34,8 +34,8 @@ public class FileDao { IMPORTANT_CATEGORY = Arrays.asList(System.getProperty("fangjia.important.category", "data_file,district,shop,office,avatar,flash,user_house,upload").split(",")); try { - filesCollection = new Mongo("fs.mongo.db.fangjia.com", 27000).getDB("fangjia_fs").getCollection("files"); - gridFs = new GridFS(filesCollection.getDB(), "fangjia_fs"); + filesCollection = new Mongo("fs.mongo.db.fangjia.com", 27000).getDB("fangjia").getCollection("files"); + gridFs = new GridFS(filesCollection.getDB(), "fangjia"); cappedCollection = new Mongo("capped.mongo.db.fangjia.com", Integer.getInteger("capped.mongo.port", 27000)).getDB("fangjia_fs").getCollection("files_capped"); } catch (Exception e) { e.printStackTrace(); diff --git a/projects/fangjia-open/src/main/webapp/H9YtlL0T8j.txt b/projects/fangjia-open/src/main/webapp/H9YtlL0T8j.txt new file mode 100644 index 000000000..a1532152f --- /dev/null +++ b/projects/fangjia-open/src/main/webapp/H9YtlL0T8j.txt @@ -0,0 +1 @@ +9995d79df0ea4a6f4d1f55fd2eeabb38 \ No newline at end of file diff --git a/projects/fangjia-open/src/main/webapp/district/districtDetail.ftl b/projects/fangjia-open/src/main/webapp/district/districtDetail.ftl index 761d749d7..32a704887 100644 --- a/projects/fangjia-open/src/main/webapp/district/districtDetail.ftl +++ b/projects/fangjia-open/src/main/webapp/district/districtDetail.ftl @@ -14,10 +14,21 @@ + - + +〈 +
    @@ -65,7 +76,7 @@
    �区租金
    -

    +

    <#if districtStatRentBos?? && districtStatRentBos?size gt 0> <#list districtStatRentBos as districtStatRentBo>

    <#if districtStatRentBo.districtStatRent??>${districtStatRentBo.districtStatRent.avgPrice} å…ƒ/月

    @@ -89,7 +100,7 @@ <#if district.outPics?? && district.outPics?size gt 0> <#list district.outPics as pics> <#if pics_index < 6> - + @@ -119,10 +130,11 @@
    <#include '/layout/footer.ftl'/> - + + diff --git a/projects/fangjia-open/src/main/webapp/report/downloadList.ftl b/projects/fangjia-open/src/main/webapp/report/downloadList.ftl index 55d2fbd97..f54286437 100644 --- a/projects/fangjia-open/src/main/webapp/report/downloadList.ftl +++ b/projects/fangjia-open/src/main/webapp/report/downloadList.ftl @@ -13,10 +13,23 @@ + -
    + +〈 + +
    diff --git a/projects/fangjia-open/src/main/webapp/static/js/autoCompletion.js b/projects/fangjia-open/src/main/webapp/static/js/autoCompletion.js index 607f70dfb..25543e105 100644 --- a/projects/fangjia-open/src/main/webapp/static/js/autoCompletion.js +++ b/projects/fangjia-open/src/main/webapp/static/js/autoCompletion.js @@ -54,7 +54,7 @@ $(function () { if ($("#t").val() != "c") { saveCookie(id, name, addr, region) } - if ($("#t").val() == "b") { + if ($("#t").val() == "b" || $("#t").val() == "gb") { location.href = "districtDetail?id=" + id+"&city="+city } else if ($("#t").val() == "c") { $('#districtSearch').val(name) @@ -122,7 +122,7 @@ function resumeHistory() { $("#searchSpan ul").empty().append(content).find("li>a.item-link").click(function () { var li = $(this).parent() var id = $(li).attr("data-id") - if ($("#t").val() == "b") { + if ($("#t").val() == "b"||$("#t").val() == "gb") { location.href = "districtDetail?id=" + id+"&city="+city } else if ($("#t").val() == "c") { location.href = "../ccbRent/index?city="+city diff --git a/projects/fangjia-open/src/main/webapp/static/js/highcharts5.0.6.js b/projects/fangjia-open/src/main/webapp/static/js/highcharts5.0.6.js new file mode 100644 index 000000000..fef4b636c --- /dev/null +++ b/projects/fangjia-open/src/main/webapp/static/js/highcharts5.0.6.js @@ -0,0 +1,385 @@ +// JavaScript Document + +/* + Highcharts JS v5.0.6 (2016-12-07) + + (c) 2009-2016 Torstein Honsi + + License: www.highcharts.com/license +*/ +(function(L,a){"object"===typeof module&&module.exports?module.exports=L.document?a(L):a:L.Highcharts=a(L)})("undefined"!==typeof window?window:this,function(L){L=function(){var a=window,D=a.document,C=a.navigator&&a.navigator.userAgent||"",G=D&&D.createElementNS&&!!D.createElementNS("http://www.w3.org/2000/svg","svg").createSVGRect,I=/(edge|msie|trident)/i.test(C)&&!window.opera,h=!G,f=/Firefox/.test(C),p=f&&4>parseInt(C.split("Firefox/")[1],10);return a.Highcharts?a.Highcharts.error(16,!0):{product:"Highcharts", +version:"5.0.6",deg2rad:2*Math.PI/360,doc:D,hasBidiBug:p,hasTouch:D&&void 0!==D.documentElement.ontouchstart,isMS:I,isWebKit:/AppleWebKit/.test(C),isFirefox:f,isTouchDevice:/(Mobile|Android|Windows Phone)/.test(C),SVG_NS:"http://www.w3.org/2000/svg",chartCount:0,seriesTypes:{},symbolSizes:{},svg:G,vml:h,win:a,charts:[],marginNames:["plotTop","marginRight","marginBottom","plotLeft"],noop:function(){}}}();(function(a){var D=[],C=a.charts,G=a.doc,I=a.win;a.error=function(h,f){h=a.isNumber(h)?"Highcharts error #"+ +h+": www.highcharts.com/errors/"+h:h;if(f)throw Error(h);I.console&&console.log(h)};a.Fx=function(a,f,p){this.options=f;this.elem=a;this.prop=p};a.Fx.prototype={dSetter:function(){var a=this.paths[0],f=this.paths[1],p=[],v=this.now,l=a.length,u;if(1===v)p=this.toD;else if(l===f.length&&1>v)for(;l--;)u=parseFloat(a[l]),p[l]=isNaN(u)?a[l]:v*parseFloat(f[l]-u)+u;else p=f;this.elem.attr("d",p,null,!0)},update:function(){var a=this.elem,f=this.prop,p=this.now,v=this.options.step;if(this[f+"Setter"])this[f+ +"Setter"]();else a.attr?a.element&&a.attr(f,p,null,!0):a.style[f]=p+this.unit;v&&v.call(a,p,this)},run:function(a,f,p){var h=this,l=function(a){return l.stopped?!1:h.step(a)},u;this.startTime=+new Date;this.start=a;this.end=f;this.unit=p;this.now=this.start;this.pos=0;l.elem=this.elem;l.prop=this.prop;l()&&1===D.push(l)&&(l.timerId=setInterval(function(){for(u=0;u=u+this.startTime){this.now=this.end;this.pos=1;this.update();a=d[this.prop]=!0;for(c in d)!0!==d[c]&&(a=!1);a&&l&&l.call(h);h=!1}else this.pos=v.easing((f-this.startTime)/u),this.now=this.start+(this.end-this.start)*this.pos,this.update(),h=!0;return h},initPath:function(h,f,p){function v(a){var e,b;for(q=a.length;q--;)e="M"===a[q]||"L"===a[q],b=/[a-zA-Z]/.test(a[q+3]),e&&b&&a.splice(q+1,0,a[q+1],a[q+2],a[q+1],a[q+ +2])}function l(a,e){for(;a.lengthd?"AM":"PM",P:12>d?"am":"pm",S:z(l.getSeconds()),L:z(Math.round(f% +1E3),3)},a.dateFormats);for(u in v)for(;-1!==h.indexOf("%"+u);)h=h.replace("%"+u,"function"===typeof v[u]?v[u](f):v[u]);return p?h.substr(0,1).toUpperCase()+h.substr(1):h};a.formatSingle=function(h,f){var p=/\.([0-9])/,v=a.defaultOptions.lang;/f$/.test(h)?(p=(p=h.match(p))?p[1]:-1,null!==f&&(f=a.numberFormat(f,p,v.decimalPoint,-1=p&&(f=[1/p]))); +for(v=0;v=h||!l&&u<=(f[v]+(f[v+1]||f[v]))/2);v++);return d*p};a.stableSort=function(a,f){var p=a.length,h,l;for(l=0;lp&&(p=a[f]);return p};a.destroyObjectProperties=function(a,f){for(var p in a)a[p]&&a[p]!==f&&a[p].destroy&& +a[p].destroy(),delete a[p]};a.discardElement=function(h){var f=a.garbageBin;f||(f=a.createElement("div"));h&&f.appendChild(h);f.innerHTML=""};a.correctFloat=function(a,f){return parseFloat(a.toPrecision(f||14))};a.setAnimation=function(h,f){f.renderer.globalAnimation=a.pick(h,f.options.chart.animation,!0)};a.animObject=function(h){return a.isObject(h)?a.merge(h):{duration:h?500:0}};a.timeUnits={millisecond:1,second:1E3,minute:6E4,hour:36E5,day:864E5,week:6048E5,month:24192E5,year:314496E5};a.numberFormat= +function(h,f,p,v){h=+h||0;f=+f;var l=a.defaultOptions.lang,u=(h.toString().split(".")[1]||"").length,d,c,n=Math.abs(h);-1===f?f=Math.min(u,20):a.isNumber(f)||(f=2);d=String(a.pInt(n.toFixed(f)));c=3h?"-":"")+(c?d.substr(0,c)+v:"");h+=d.substr(c).replace(/(\d{3})(?=\d)/g,"$1"+v);f&&(v=Math.abs(n-d+Math.pow(10,-Math.max(f,u)-1)),h+=p+v.toFixed(f).slice(2));return h};Math.easeInOutSine=function(a){return-.5*(Math.cos(Math.PI* +a)-1)};a.getStyle=function(h,f){return"width"===f?Math.min(h.offsetWidth,h.scrollWidth)-a.getStyle(h,"padding-left")-a.getStyle(h,"padding-right"):"height"===f?Math.min(h.offsetHeight,h.scrollHeight)-a.getStyle(h,"padding-top")-a.getStyle(h,"padding-bottom"):(h=I.getComputedStyle(h,void 0))&&a.pInt(h.getPropertyValue(f))};a.inArray=function(a,f){return f.indexOf?f.indexOf(a):[].indexOf.call(f,a)};a.grep=function(a,f){return[].filter.call(a,f)};a.find=function(a,f){return[].find.call(a,f)};a.map=function(a, +f){for(var p=[],h=0,l=a.length;hf;f++)v[f]+=h(255*a),0>v[f]&&(v[f]=0),255E.width)E={width:0, +height:0}}else E=this.htmlGetBBox();H.isSVG&&(a=E.width,H=E.height,e&&c&&"11px"===c.fontSize&&"16.9"===H.toPrecision(3)&&(E.height=H=14),g&&(E.width=Math.abs(H*Math.sin(k))+Math.abs(a*Math.cos(k)),E.height=Math.abs(H*Math.cos(k))+Math.abs(a*Math.sin(k))));if(x&&0]*>/g,"")))},textSetter:function(a){a!==this.textStr&&(delete this.bBox,this.textStr=a,this.added&&this.renderer.buildText(this))},fillSetter:function(a, +g,e){"string"===typeof a?e.setAttribute(g,a):a&&this.colorGradient(a,g,e)},visibilitySetter:function(a,g,e){"inherit"===a?e.removeAttribute(g):e.setAttribute(g,a)},zIndexSetter:function(a,g){var e=this.renderer,k=this.parentGroup,b=(k||e).element||e.box,c,B=this.element,H;c=this.added;var r;u(a)&&(B.zIndex=a,a=+a,this[g]===a&&(c=!1),this[g]=a);if(c){(a=this.zIndex)&&k&&(k.handleZ=!0);g=b.childNodes;for(r=0;ra||!u(a)&&u(c)||0>a&&!u(c)&&b!==e.box)&&(b.insertBefore(B, +k),H=!0);H||b.appendChild(B)}return H},_defaultSetter:function(a,g,e){e.setAttribute(g,a)}};D.prototype.yGetter=D.prototype.xGetter;D.prototype.translateXSetter=D.prototype.translateYSetter=D.prototype.rotationSetter=D.prototype.verticalAlignSetter=D.prototype.scaleXSetter=D.prototype.scaleYSetter=function(a,g){this[g]=a;this.doTransform=!0};D.prototype["stroke-widthSetter"]=D.prototype.strokeSetter=function(a,g,e){this[g]=a;this.stroke&&this["stroke-width"]?(D.prototype.fillSetter.call(this,this.stroke, +"stroke",e),e.setAttribute("stroke-width",this["stroke-width"]),this.hasStroke=!0):"stroke-width"===g&&0===a&&this.hasStroke&&(e.removeAttribute("stroke"),this.hasStroke=!1)};C=a.SVGRenderer=function(){this.init.apply(this,arguments)};C.prototype={Element:D,SVG_NS:S,init:function(a,g,e,k,b,c){var B;k=this.createElement("svg").attr({version:"1.1","class":"highcharts-root"}).css(this.getStyle(k));B=k.element;a.appendChild(B);-1===a.innerHTML.indexOf("xmlns")&&h(B,"xmlns",this.SVG_NS);this.isSVG=!0; +this.box=B;this.boxWrapper=k;this.alignedObjects=[];this.url=(F||A)&&n.getElementsByTagName("base").length?R.location.href.replace(/#.*?$/,"").replace(/([\('\)])/g,"\\$1").replace(/ /g,"%20"):"";this.createElement("desc").add().element.appendChild(n.createTextNode("Created with Highcharts 5.0.6"));this.defs=this.createElement("defs").add();this.allowHTML=c;this.forExport=b;this.gradients={};this.cache={};this.cacheKeys=[];this.imgCount=0;this.setSize(g,e,!1);var H;F&&a.getBoundingClientRect&&(g=function(){v(a, +{left:0,top:0});H=a.getBoundingClientRect();v(a,{left:Math.ceil(H.left)-H.left+"px",top:Math.ceil(H.top)-H.top+"px"})},g(),this.unSubPixelFix=G(R,"resize",g))},getStyle:function(a){return this.style=t({fontFamily:'"Lucida Grande", "Lucida Sans Unicode", Arial, Helvetica, sans-serif',fontSize:"12px"},a)},setStyle:function(a){this.boxWrapper.css(this.getStyle(a))},isHidden:function(){return!this.boxWrapper.getBBox().width},destroy:function(){var a=this.defs;this.box=null;this.boxWrapper=this.boxWrapper.destroy(); +c(this.gradients||{});this.gradients=null;a&&(this.defs=a.destroy());this.unSubPixelFix&&this.unSubPixelFix();return this.alignedObjects=null},createElement:function(a){var g=new this.Element;g.init(this,a);return g},draw:w,getRadialAttr:function(a,g){return{cx:a[0]-a[2]/2+g.cx*a[2],cy:a[1]-a[2]/2+g.cy*a[2],r:g.r*a[2]}},buildText:function(a){for(var g=a.element,e=this,k=e.forExport,c=K(a.textStr,"").toString(),r=-1!==c.indexOf("\x3c"),m=g.childNodes,w,E,q,x,d=h(g,"x"),t=a.styles,A=a.textWidth,z=t&& +t.lineHeight,l=t&&t.textOutline,F=t&&"ellipsis"===t.textOverflow,f=m.length,u=A&&!a.added&&this.box,p=function(a){var k;k=/(px|em)$/.test(a&&a.style.fontSize)?a.style.fontSize:t&&t.fontSize||e.style.fontSize||12;return z?J(z):e.fontMetrics(k,a.getAttribute("style")?a:g).h};f--;)g.removeChild(m[f]);r||l||F||A||-1!==c.indexOf(" ")?(w=/<.*class="([^"]+)".*>/,E=/<.*style="([^"]+)".*>/,q=/<.*href="(http[^"]+)".*>/,u&&u.appendChild(g),c=r?c.replace(/<(b|strong)>/g,'\x3cspan style\x3d"font-weight:bold"\x3e').replace(/<(i|em)>/g, +'\x3cspan style\x3d"font-style:italic"\x3e').replace(//g,"\x3c/span\x3e").split(//g):[c],c=b(c,function(a){return""!==a}),y(c,function(b,c){var r,H=0;b=b.replace(/^\s+|\s+$/g,"").replace(//g,"\x3c/span\x3e|||");r=b.split("|||");y(r,function(b){if(""!==b||1===r.length){var m={},l=n.createElementNS(e.SVG_NS,"tspan"),z,f;w.test(b)&&(z=b.match(w)[1],h(l,"class",z));E.test(b)&&(f=b.match(E)[1].replace(/(;| |^)color([ :])/, +"$1fill$2"),h(l,"style",f));q.test(b)&&!k&&(h(l,"onclick",'location.href\x3d"'+b.match(q)[1]+'"'),v(l,{cursor:"pointer"}));b=(b.replace(/<(.|\n)*?>/g,"")||" ").replace(/</g,"\x3c").replace(/>/g,"\x3e");if(" "!==b){l.appendChild(n.createTextNode(b));H?m.dx=0:c&&null!==d&&(m.x=d);h(l,m);g.appendChild(l);!H&&c&&(!B&&k&&v(l,{display:"block"}),h(l,"dy",p(l)));if(A){m=b.replace(/([^\^])-/g,"$1- ").split(" ");z="nowrap"===t.whiteSpace;for(var K=1A,void 0===x&&(x=u),F&&x?(N/=2,""===O||!u&&.5>N?m=[]:(O=b.substring(0,O.length+(u?-1:1)*Math.ceil(N)),m=[O+(3A&&(A=y)),m.length&& +l.appendChild(n.createTextNode(m.join(" ").replace(/- /g,"-")));a.rotation=P}H++}}})}),x&&a.attr("title",a.textStr),u&&u.removeChild(g),l&&a.applyTextOutline&&a.applyTextOutline(l)):g.appendChild(n.createTextNode(c.replace(/</g,"\x3c").replace(/>/g,"\x3e")))},getContrast:function(a){a=p(a).rgba;return 510e?k>g+B&&kr?k>g+B&&kb&&r>a+B&&rk&&r>a+B&&ra?a+3:Math.round(1.2* +a);return{h:g,b:Math.round(.8*g),f:a}},rotCorr:function(a,g,e){var b=a;g&&e&&(b=Math.max(b*Math.cos(g*d),4));return{x:-a/3*Math.sin(g*d),y:b}},label:function(a,g,e,b,c,B,r,m,w){var q=this,x=q.g("button"!==w&&"label"),d=x.text=q.text("",0,0,r).attr({zIndex:1}),H,n,l=0,A=3,z=0,F,f,K,p,J,h={},M,S,E=/^url\((.*?)\)$/.test(b),v=E,P,R,O,Q;w&&x.addClass("highcharts-"+w);v=E;P=function(){return(M||0)%2/2};R=function(){var a=d.element.style,g={};n=(void 0===F||void 0===f||J)&&u(d.textStr)&&d.getBBox();x.width= +(F||n.width||0)+2*A+z;x.height=(f||n.height||0)+2*A;S=A+q.fontMetrics(a&&a.fontSize,d).b;v&&(H||(x.box=H=q.symbols[b]||E?q.symbol(b):q.rect(),H.addClass(("button"===w?"":"highcharts-label-box")+(w?" highcharts-"+w+"-box":"")),H.add(x),a=P(),g.x=a,g.y=(m?-S:0)+a),g.width=Math.round(x.width),g.height=Math.round(x.height),H.attr(t(g,h)),h={})};O=function(){var a=z+A,g;g=m?0:S;u(F)&&n&&("center"===J||"right"===J)&&(a+={center:.5,right:1}[J]*(F-n.width));if(a!==d.x||g!==d.y)d.attr("x",a),void 0!==g&&d.attr("y", +g);d.x=a;d.y=g};Q=function(a,g){H?H.attr(a,g):h[a]=g};x.onAdd=function(){d.add(x);x.attr({text:a||0===a?a:"",x:g,y:e});H&&u(c)&&x.attr({anchorX:c,anchorY:B})};x.widthSetter=function(a){F=a};x.heightSetter=function(a){f=a};x["text-alignSetter"]=function(a){J=a};x.paddingSetter=function(a){u(a)&&a!==A&&(A=x.padding=a,O())};x.paddingLeftSetter=function(a){u(a)&&a!==z&&(z=a,O())};x.alignSetter=function(a){a={left:0,center:.5,right:1}[a];a!==l&&(l=a,n&&x.attr({x:K}))};x.textSetter=function(a){void 0!== +a&&d.textSetter(a);R();O()};x["stroke-widthSetter"]=function(a,g){a&&(v=!0);M=this["stroke-width"]=a;Q(g,a)};x.strokeSetter=x.fillSetter=x.rSetter=function(a,g){"fill"===g&&a&&(v=!0);Q(g,a)};x.anchorXSetter=function(a,g){c=a;Q(g,Math.round(a)-P()-K)};x.anchorYSetter=function(a,g){B=a;Q(g,a-p)};x.xSetter=function(a){x.x=a;l&&(a-=l*((F||n.width)+2*A));K=Math.round(a);x.attr("translateX",K)};x.ySetter=function(a){p=x.y=Math.round(a);x.attr("translateY",p)};var V=x.css;return t(x,{css:function(a){if(a){var g= +{};a=k(a);y(x.textProps,function(e){void 0!==a[e]&&(g[e]=a[e],delete a[e])});d.css(g)}return V.call(x,a)},getBBox:function(){return{width:n.width+2*A,height:n.height+2*A,x:n.x-A,y:n.y-A}},shadow:function(a){a&&(R(),H&&H.shadow(a));return x},destroy:function(){N(x.element,"mouseenter");N(x.element,"mouseleave");d&&(d=d.destroy());H&&(H=H.destroy());D.prototype.destroy.call(x);x=q=R=O=Q=null}})}};a.Renderer=C})(L);(function(a){var D=a.attr,C=a.createElement,G=a.css,I=a.defined,h=a.each,f=a.extend,p= +a.isFirefox,v=a.isMS,l=a.isWebKit,u=a.pInt,d=a.SVGRenderer,c=a.win,n=a.wrap;f(a.SVGElement.prototype,{htmlCss:function(a){var c=this.element;if(c=a&&"SPAN"===c.tagName&&a.width)delete a.width,this.textWidth=c,this.updateTransform();a&&"ellipsis"===a.textOverflow&&(a.whiteSpace="nowrap",a.overflow="hidden");this.styles=f(this.styles,a);G(this.element,a);return this},htmlGetBBox:function(){var a=this.element;"text"===a.nodeName&&(a.style.position="absolute");return{x:a.offsetLeft,y:a.offsetTop,width:a.offsetWidth, +height:a.offsetHeight}},htmlUpdateTransform:function(){if(this.added){var a=this.renderer,c=this.element,m=this.translateX||0,b=this.translateY||0,q=this.x||0,d=this.y||0,n=this.textAlign||"left",e={left:0,center:.5,right:1}[n],r=this.styles;G(c,{marginLeft:m,marginTop:b});this.shadows&&h(this.shadows,function(a){G(a,{marginLeft:m+1,marginTop:b+1})});this.inverted&&h(c.childNodes,function(e){a.invertChild(e,c)});if("SPAN"===c.tagName){var x=this.rotation,A=u(this.textWidth),k=r&&r.whiteSpace,w=[x, +n,c.innerHTML,this.textWidth,this.textAlign].join();w!==this.cTT&&(r=a.fontMetrics(c.style.fontSize).b,I(x)&&this.setSpanRotation(x,e,r),G(c,{width:"",whiteSpace:k||"nowrap"}),c.offsetWidth>A&&/[ \-]/.test(c.textContent||c.innerText)&&G(c,{width:A+"px",display:"block",whiteSpace:k||"normal"}),this.getSpanCorrection(c.offsetWidth,r,e,x,n));G(c,{left:q+(this.xCorr||0)+"px",top:d+(this.yCorr||0)+"px"});l&&(r=c.offsetHeight);this.cTT=w}}else this.alignOnAdd=!0},setSpanRotation:function(a,d,m){var b={}, +q=v?"-ms-transform":l?"-webkit-transform":p?"MozTransform":c.opera?"-o-transform":"";b[q]=b.transform="rotate("+a+"deg)";b[q+(p?"Origin":"-origin")]=b.transformOrigin=100*d+"% "+m+"px";G(this.element,b)},getSpanCorrection:function(a,c,m){this.xCorr=-a*m;this.yCorr=-c}});f(d.prototype,{html:function(a,c,m){var b=this.createElement("span"),q=b.element,d=b.renderer,l=d.isSVG,e=function(a,e){h(["opacity","visibility"],function(b){n(a,b+"Setter",function(a,b,c,r){a.call(this,b,c,r);e[c]=b})})};b.textSetter= +function(a){a!==q.innerHTML&&delete this.bBox;q.innerHTML=this.textStr=a;b.htmlUpdateTransform()};l&&e(b,b.element.style);b.xSetter=b.ySetter=b.alignSetter=b.rotationSetter=function(a,e){"align"===e&&(e="textAlign");b[e]=a;b.htmlUpdateTransform()};b.attr({text:a,x:Math.round(c),y:Math.round(m)}).css({fontFamily:this.style.fontFamily,fontSize:this.style.fontSize,position:"absolute"});q.style.whiteSpace="nowrap";b.css=b.htmlCss;l&&(b.add=function(a){var c,r=d.box.parentNode,k=[];if(this.parentGroup= +a){if(c=a.div,!c){for(;a;)k.push(a),a=a.parentGroup;h(k.reverse(),function(a){var m,x=D(a.element,"class");x&&(x={className:x});c=a.div=a.div||C("div",x,{position:"absolute",left:(a.translateX||0)+"px",top:(a.translateY||0)+"px",display:a.display,opacity:a.opacity,pointerEvents:a.styles&&a.styles.pointerEvents},c||r);m=c.style;f(a,{on:function(){b.on.apply({element:k[0].div},arguments);return a},translateXSetter:function(e,g){m.left=e+"px";a[g]=e;a.doTransform=!0},translateYSetter:function(e,g){m.top= +e+"px";a[g]=e;a.doTransform=!0}});e(a,m)})}}else c=r;c.appendChild(q);b.added=!0;b.alignOnAdd&&b.htmlUpdateTransform();return b});return b}})})(L);(function(a){var D,C,G=a.createElement,I=a.css,h=a.defined,f=a.deg2rad,p=a.discardElement,v=a.doc,l=a.each,u=a.erase,d=a.extend;D=a.extendClass;var c=a.isArray,n=a.isNumber,y=a.isObject,t=a.merge;C=a.noop;var m=a.pick,b=a.pInt,q=a.SVGElement,z=a.SVGRenderer,F=a.win;a.svg||(C={docMode8:v&&8===v.documentMode,init:function(a,b){var e=["\x3c",b,' filled\x3d"f" stroked\x3d"f"'], +c=["position: ","absolute",";"],k="div"===b;("shape"===b||k)&&c.push("left:0;top:0;width:1px;height:1px;");c.push("visibility: ",k?"hidden":"visible");e.push(' style\x3d"',c.join(""),'"/\x3e');b&&(e=k||"span"===b||"img"===b?e.join(""):a.prepVML(e),this.element=G(e));this.renderer=a},add:function(a){var e=this.renderer,b=this.element,c=e.box,k=a&&a.inverted,c=a?a.element||a:c;a&&(this.parentGroup=a);k&&e.invertChild(b,c);c.appendChild(b);this.added=!0;this.alignOnAdd&&!this.deferUpdateTransform&&this.updateTransform(); +if(this.onAdd)this.onAdd();this.className&&this.attr("class",this.className);return this},updateTransform:q.prototype.htmlUpdateTransform,setSpanRotation:function(){var a=this.rotation,b=Math.cos(a*f),c=Math.sin(a*f);I(this.element,{filter:a?["progid:DXImageTransform.Microsoft.Matrix(M11\x3d",b,", M12\x3d",-c,", M21\x3d",c,", M22\x3d",b,", sizingMethod\x3d'auto expand')"].join(""):"none"})},getSpanCorrection:function(a,b,c,q,k){var e=q?Math.cos(q*f):1,r=q?Math.sin(q*f):0,x=m(this.elemHeight,this.element.offsetHeight), +d;this.xCorr=0>e&&-a;this.yCorr=0>r&&-x;d=0>e*r;this.xCorr+=r*b*(d?1-c:c);this.yCorr-=e*b*(q?d?c:1-c:1);k&&"left"!==k&&(this.xCorr-=a*c*(0>e?-1:1),q&&(this.yCorr-=x*c*(0>r?-1:1)),I(this.element,{textAlign:k}))},pathToVML:function(a){for(var e=a.length,b=[];e--;)n(a[e])?b[e]=Math.round(10*a[e])-5:"Z"===a[e]?b[e]="x":(b[e]=a[e],!a.isArc||"wa"!==a[e]&&"at"!==a[e]||(b[e+5]===b[e+7]&&(b[e+7]+=a[e+7]>a[e+5]?1:-1),b[e+6]===b[e+8]&&(b[e+8]+=a[e+8]>a[e+6]?1:-1)));return b.join(" ")||"x"},clip:function(a){var e= +this,b;a?(b=a.members,u(b,e),b.push(e),e.destroyClip=function(){u(b,e)},a=a.getCSS(e)):(e.destroyClip&&e.destroyClip(),a={clip:e.docMode8?"inherit":"rect(auto)"});return e.css(a)},css:q.prototype.htmlCss,safeRemoveChild:function(a){a.parentNode&&p(a)},destroy:function(){this.destroyClip&&this.destroyClip();return q.prototype.destroy.apply(this)},on:function(a,b){this.element["on"+a]=function(){var a=F.event;a.target=a.srcElement;b(a)};return this},cutOffPath:function(a,c){var e;a=a.split(/[ ,]/); +e=a.length;if(9===e||11===e)a[e-4]=a[e-2]=b(a[e-2])-10*c;return a.join(" ")},shadow:function(a,c,q){var e=[],k,r=this.element,d=this.renderer,x,n=r.style,g,B=r.path,l,t,z,f;B&&"string"!==typeof B.value&&(B="x");t=B;if(a){z=m(a.width,3);f=(a.opacity||.15)/z;for(k=1;3>=k;k++)l=2*z+1-2*k,q&&(t=this.cutOffPath(B.value,l+.5)),g=['\x3cshape isShadow\x3d"true" strokeweight\x3d"',l,'" filled\x3d"false" path\x3d"',t,'" coordsize\x3d"10 10" style\x3d"',r.style.cssText,'" /\x3e'],x=G(d.prepVML(g),null,{left:b(n.left)+ +m(a.offsetX,1),top:b(n.top)+m(a.offsetY,1)}),q&&(x.cutOff=l+1),g=['\x3cstroke color\x3d"',a.color||"#000000",'" opacity\x3d"',f*k,'"/\x3e'],G(d.prepVML(g),null,null,x),c?c.element.appendChild(x):r.parentNode.insertBefore(x,r),e.push(x);this.shadows=e}return this},updateShadows:C,setAttr:function(a,b){this.docMode8?this.element[a]=b:this.element.setAttribute(a,b)},classSetter:function(a){(this.added?this.element:this).className=a},dashstyleSetter:function(a,b,c){(c.getElementsByTagName("stroke")[0]|| +G(this.renderer.prepVML(["\x3cstroke/\x3e"]),null,null,c))[b]=a||"solid";this[b]=a},dSetter:function(a,b,c){var e=this.shadows;a=a||[];this.d=a.join&&a.join(" ");c.path=a=this.pathToVML(a);if(e)for(c=e.length;c--;)e[c].path=e[c].cutOff?this.cutOffPath(a,e[c].cutOff):a;this.setAttr(b,a)},fillSetter:function(a,b,c){var e=c.nodeName;"SPAN"===e?c.style.color=a:"IMG"!==e&&(c.filled="none"!==a,this.setAttr("fillcolor",this.renderer.color(a,c,b,this)))},"fill-opacitySetter":function(a,b,c){G(this.renderer.prepVML(["\x3c", +b.split("-")[0],' opacity\x3d"',a,'"/\x3e']),null,null,c)},opacitySetter:C,rotationSetter:function(a,b,c){c=c.style;this[b]=c[b]=a;c.left=-Math.round(Math.sin(a*f)+1)+"px";c.top=Math.round(Math.cos(a*f))+"px"},strokeSetter:function(a,b,c){this.setAttr("strokecolor",this.renderer.color(a,c,b,this))},"stroke-widthSetter":function(a,b,c){c.stroked=!!a;this[b]=a;n(a)&&(a+="px");this.setAttr("strokeweight",a)},titleSetter:function(a,b){this.setAttr(b,a)},visibilitySetter:function(a,b,c){"inherit"===a&& +(a="visible");this.shadows&&l(this.shadows,function(c){c.style[b]=a});"DIV"===c.nodeName&&(a="hidden"===a?"-999em":0,this.docMode8||(c.style[b]=a?"visible":"hidden"),b="top");c.style[b]=a},xSetter:function(a,b,c){this[b]=a;"x"===b?b="left":"y"===b&&(b="top");this.updateClipping?(this[b]=a,this.updateClipping()):c.style[b]=a},zIndexSetter:function(a,b,c){c.style[b]=a}},C["stroke-opacitySetter"]=C["fill-opacitySetter"],a.VMLElement=C=D(q,C),C.prototype.ySetter=C.prototype.widthSetter=C.prototype.heightSetter= +C.prototype.xSetter,C={Element:C,isIE8:-1h[0]&&b.push([1,h[1]]);l(b,function(g,b){d.test(g[1])?(r=a.color(g[1]),B=r.get("rgb"),t=r.get("a")):(B=g[1],t=1);y.push(100*g[0]+"% "+B);b?(H=t,A=B):(F=t,u=B)});if("fill"===m)if("gradient"===x)m=z.x1||z[0]||0,b=z.y1||z[1]||0,f=z.x2||z[2]||0,z=z.y2||z[3]||0,p='angle\x3d"'+(90-180*Math.atan((z-b)/(f-m))/Math.PI)+'"', +v();else{var g=z.r,C=2*g,D=2*g,I=z.cx,U=z.cy,L=c.radialReference,T,g=function(){L&&(T=q.getBBox(),I+=(L[0]-T.x)/T.width-.5,U+=(L[1]-T.y)/T.height-.5,C*=L[2]/T.width,D*=L[2]/T.height);p='src\x3d"'+a.getOptions().global.VMLRadialGradientURL+'" size\x3d"'+C+","+D+'" origin\x3d"0.5,0.5" position\x3d"'+I+","+U+'" color2\x3d"'+u+'" ';v()};q.added?g():q.onAdd=g;g=A}else g=B}else d.test(b)&&"IMG"!==c.tagName?(r=a.color(b),q[m+"-opacitySetter"](r.get("a"),m,c),g=r.get("rgb")):(g=c.getElementsByTagName(m), +g.length&&(g[0].opacity=1,g[0].type="solid"),g=b);return g},prepVML:function(a){var b=this.isIE8;a=a.join("");b?(a=a.replace("/\x3e",' xmlns\x3d"urn:schemas-microsoft-com:vml" /\x3e'),a=-1===a.indexOf('style\x3d"')?a.replace("/\x3e",' style\x3d"display:inline-block;behavior:url(#default#VML);" /\x3e'):a.replace('style\x3d"','style\x3d"display:inline-block;behavior:url(#default#VML);')):a=a.replace("\x3c","\x3chcv:");return a},text:z.prototype.html,path:function(a){var b={coordsize:"10 10"};c(a)?b.d= +a:y(a)&&d(b,a);return this.createElement("shape").attr(b)},circle:function(a,b,c){var e=this.symbol("circle");y(a)&&(c=a.r,b=a.y,a=a.x);e.isCircle=!0;e.r=c;return e.attr({x:a,y:b})},g:function(a){var b;a&&(b={className:"highcharts-"+a,"class":"highcharts-"+a});return this.createElement("div").attr(b)},image:function(a,b,c,m,k){var e=this.createElement("img").attr({src:a});1t&&h-m*bc&&(e=Math.round((d-h)/Math.cos(t*p)));else if(d=h+(1-m)*b,h-m*bc&&(z=c-a.x+z*m,F=-1),z=Math.min(q, +z),zz||l.autoRotation&&(y.styles||{}).width)e=z;e&&(r.width=e,(l.options.labels.style||{}).textOverflow||(r.textOverflow="ellipsis"),y.css(r))},getPosition:function(a,f,h,d){var c=this.axis,n=c.chart,l=d&&n.oldChartHeight||n.chartHeight;return{x:a?c.translate(f+h,null,null,d)+c.transB:c.left+c.offset+(c.opposite?(d&&n.oldChartWidth||n.chartWidth)-c.right-c.left:0),y:a?l-c.bottom+c.offset-(c.opposite?c.height:0):l-c.translate(f+h,null, +null,d)-c.transB}},getLabelPosition:function(a,f,h,d,c,n,y,t){var m=this.axis,b=m.transA,q=m.reversed,z=m.staggerLines,l=m.tickRotCorr||{x:0,y:0},e=c.y;C(e)||(e=0===m.side?h.rotation?-8:-h.getBBox().height:2===m.side?l.y+8:Math.cos(h.rotation*p)*(l.y-h.getBBox(!1,0).height/2));a=a+c.x+l.x-(n&&d?n*b*(q?-1:1):0);f=f+e-(n&&!d?n*b*(q?1:-1):0);z&&(h=y/(t||1)%z,m.opposite&&(h=z-h-1),f+=m.labelOffset/z*h);return{x:a,y:Math.round(f)}},getMarkPath:function(a,f,h,d,c,n){return n.crispLine(["M",a,f,"L",a+(c? +0:-h),f+(c?h:0)],d)},render:function(a,l,h){var d=this.axis,c=d.options,n=d.chart.renderer,p=d.horiz,t=this.type,m=this.label,b=this.pos,q=c.labels,z=this.gridLine,F=t?t+"Tick":"tick",e=d.tickSize(F),r=this.mark,x=!r,A=q.step,k={},w=!0,K=d.tickmarkOffset,J=this.getPosition(p,b,K,l),u=J.x,J=J.y,g=p&&u===d.pos+d.len||!p&&J===d.pos?-1:1,B=t?t+"Grid":"grid",S=c[B+"LineWidth"],M=c[B+"LineColor"],v=c[B+"LineDashStyle"],B=f(c[F+"Width"],!t&&d.isXAxis?1:0),F=c[F+"Color"];h=f(h,1);this.isActive=!0;z||(k.stroke= +M,k["stroke-width"]=S,v&&(k.dashstyle=v),t||(k.zIndex=1),l&&(k.opacity=0),this.gridLine=z=n.path().attr(k).addClass("highcharts-"+(t?t+"-":"")+"grid-line").add(d.gridGroup));if(!l&&z&&(b=d.getPlotLinePath(b+K,z.strokeWidth()*g,l,!0)))z[this.isNew?"attr":"animate"]({d:b,opacity:h});e&&(d.opposite&&(e[0]=-e[0]),x&&(this.mark=r=n.path().addClass("highcharts-"+(t?t+"-":"")+"tick").add(d.axisGroup),r.attr({stroke:F,"stroke-width":B})),r[x?"attr":"animate"]({d:this.getMarkPath(u,J,e[0],r.strokeWidth()* +g,p,n),opacity:h}));m&&I(u)&&(m.xy=J=this.getLabelPosition(u,J,m,p,q,K,a,A),this.isFirst&&!this.isLast&&!f(c.showFirstLabel,1)||this.isLast&&!this.isFirst&&!f(c.showLastLabel,1)?w=!1:!p||d.isRadial||q.step||q.rotation||l||0===h||this.handleOverflow(J),A&&a%A&&(w=!1),w&&I(J.y)?(J.opacity=h,m[this.isNew?"attr":"animate"](J)):m.attr("y",-9999),this.isNew=!1)},destroy:function(){G(this,this.axis)}}})(L);(function(a){var D=a.addEvent,C=a.animObject,G=a.arrayMax,I=a.arrayMin,h=a.AxisPlotLineOrBandExtension, +f=a.color,p=a.correctFloat,v=a.defaultOptions,l=a.defined,u=a.deg2rad,d=a.destroyObjectProperties,c=a.each,n=a.extend,y=a.fireEvent,t=a.format,m=a.getMagnitude,b=a.grep,q=a.inArray,z=a.isArray,F=a.isNumber,e=a.isString,r=a.merge,x=a.normalizeTickInterval,A=a.pick,k=a.PlotLineOrBand,w=a.removeEvent,K=a.splat,J=a.syncTimeout,N=a.Tick;a.Axis=function(){this.init.apply(this,arguments)};a.Axis.prototype={defaultOptions:{dateTimeLabelFormats:{millisecond:"%H:%M:%S.%L",second:"%H:%M:%S",minute:"%H:%M",hour:"%H:%M", +day:"%e. %b",week:"%e. %b",month:"%b '%y",year:"%Y"},endOnTick:!1,labels:{enabled:!0,style:{color:"#666666",cursor:"default",fontSize:"11px"},x:0},minPadding:.01,maxPadding:.01,minorTickLength:2,minorTickPosition:"outside",startOfWeek:1,startOnTick:!1,tickLength:10,tickmarkPlacement:"between",tickPixelInterval:100,tickPosition:"outside",title:{align:"middle",style:{color:"#666666"}},type:"linear",minorGridLineColor:"#f2f2f2",minorGridLineWidth:1,minorTickColor:"#999999",lineColor:"#ccd6eb",lineWidth:1, +gridLineColor:"#e6e6e6",tickColor:"#ccd6eb"},defaultYAxisOptions:{endOnTick:!0,tickPixelInterval:72,showLastLabel:!0,labels:{x:-8},maxPadding:.05,minPadding:.05,startOnTick:!0,title:{rotation:270,text:"Values"},stackLabels:{enabled:!1,formatter:function(){return a.numberFormat(this.total,-1)},style:{fontSize:"11px",fontWeight:"bold",color:"#000000",textOutline:"1px contrast"}},gridLineWidth:1,lineWidth:0},defaultLeftAxisOptions:{labels:{x:-15},title:{rotation:270}},defaultRightAxisOptions:{labels:{x:15}, +title:{rotation:90}},defaultBottomAxisOptions:{labels:{autoRotation:[-45],x:0},title:{rotation:0}},defaultTopAxisOptions:{labels:{autoRotation:[-45],x:0},title:{rotation:0}},init:function(a,b){var g=b.isX;this.chart=a;this.horiz=a.inverted?!g:g;this.isXAxis=g;this.coll=this.coll||(g?"xAxis":"yAxis");this.opposite=b.opposite;this.side=b.side||(this.horiz?this.opposite?0:2:this.opposite?1:3);this.setOptions(b);var c=this.options,e=c.type;this.labelFormatter=c.labels.formatter||this.defaultLabelFormatter; +this.userOptions=b;this.minPixelPadding=0;this.reversed=c.reversed;this.visible=!1!==c.visible;this.zoomEnabled=!1!==c.zoomEnabled;this.hasNames="category"===e||!0===c.categories;this.categories=c.categories||this.hasNames;this.names=this.names||[];this.isLog="logarithmic"===e;this.isDatetimeAxis="datetime"===e;this.isLinked=l(c.linkedTo);this.ticks={};this.labelEdge=[];this.minorTicks={};this.plotLinesAndBands=[];this.alternateBands={};this.len=0;this.minRange=this.userMinRange=c.minRange||c.maxZoom; +this.range=c.range;this.offset=c.offset||0;this.stacks={};this.oldStacks={};this.stacksTouched=0;this.min=this.max=null;this.crosshair=A(c.crosshair,K(a.options.tooltip.crosshairs)[g?0:1],!1);var k;b=this.options.events;-1===q(this,a.axes)&&(g?a.axes.splice(a.xAxis.length,0,this):a.axes.push(this),a[this.coll].push(this));this.series=this.series||[];a.inverted&&g&&void 0===this.reversed&&(this.reversed=!0);this.removePlotLine=this.removePlotBand=this.removePlotBandOrLine;for(k in b)D(this,k,b[k]); +this.isLog&&(this.val2lin=this.log2lin,this.lin2val=this.lin2log)},setOptions:function(a){this.options=r(this.defaultOptions,"yAxis"===this.coll&&this.defaultYAxisOptions,[this.defaultTopAxisOptions,this.defaultRightAxisOptions,this.defaultBottomAxisOptions,this.defaultLeftAxisOptions][this.side],r(v[this.coll],a))},defaultLabelFormatter:function(){var g=this.axis,b=this.value,c=g.categories,e=this.dateTimeLabelFormat,k=v.lang,m=k.numericSymbols,k=k.numericSymbolMagnitude||1E3,q=m&&m.length,d,r=g.options.labels.format, +g=g.isLog?b:g.tickInterval;if(r)d=t(r,this);else if(c)d=b;else if(e)d=a.dateFormat(e,b);else if(q&&1E3<=g)for(;q--&&void 0===d;)c=Math.pow(k,q+1),g>=c&&0===10*b%c&&null!==m[q]&&0!==b&&(d=a.numberFormat(b/c,-1)+m[q]);void 0===d&&(d=1E4<=Math.abs(b)?a.numberFormat(b,-1):a.numberFormat(b,-1,void 0,""));return d},getSeriesExtremes:function(){var a=this,e=a.chart;a.hasVisibleSeries=!1;a.dataMin=a.dataMax=a.threshold=null;a.softThreshold=!a.isXAxis;a.buildStacks&&a.buildStacks();c(a.series,function(g){if(g.visible|| +!e.options.chart.ignoreHiddenSeries){var c=g.options,k=c.threshold,B;a.hasVisibleSeries=!0;a.isLog&&0>=k&&(k=null);if(a.isXAxis)c=g.xData,c.length&&(g=I(c),F(g)||g instanceof Date||(c=b(c,function(a){return F(a)}),g=I(c)),a.dataMin=Math.min(A(a.dataMin,c[0]),g),a.dataMax=Math.max(A(a.dataMax,c[0]),G(c)));else if(g.getExtremes(),B=g.dataMax,g=g.dataMin,l(g)&&l(B)&&(a.dataMin=Math.min(A(a.dataMin,g),g),a.dataMax=Math.max(A(a.dataMax,B),B)),l(k)&&(a.threshold=k),!c.softThreshold||a.isLog)a.softThreshold= +!1}})},translate:function(a,b,c,e,k,m){var g=this.linkedParent||this,B=1,q=0,d=e?g.oldTransA:g.transA;e=e?g.oldMin:g.min;var r=g.minPixelPadding;k=(g.isOrdinal||g.isBroken||g.isLog&&k)&&g.lin2val;d||(d=g.transA);c&&(B*=-1,q=g.len);g.reversed&&(B*=-1,q-=B*(g.sector||g.len));b?(a=(a*B+q-r)/d+e,k&&(a=g.lin2val(a))):(k&&(a=g.val2lin(a)),a=B*(a-e)*d+q+B*r+(F(m)?d*m:0));return a},toPixels:function(a,b){return this.translate(a,!1,!this.horiz,null,!0)+(b?0:this.pos)},toValue:function(a,b){return this.translate(a- +(b?0:this.pos),!0,!this.horiz,null,!0)},getPlotLinePath:function(a,b,c,e,k){var g=this.chart,B=this.left,m=this.top,q,d,r=c&&g.oldChartHeight||g.chartHeight,n=c&&g.oldChartWidth||g.chartWidth,f;q=this.transB;var w=function(a,g,b){if(ab)e?a=Math.min(Math.max(g,a),b):f=!0;return a};k=A(k,this.translate(a,null,null,c));a=c=Math.round(k+q);q=d=Math.round(r-k-q);F(k)?this.horiz?(q=m,d=r-this.bottom,a=c=w(a,B,B+this.width)):(a=B,c=n-this.right,q=d=w(q,m,m+this.height)):f=!0;return f&&!e?null:g.renderer.crispLine(["M", +a,q,"L",c,d],b||1)},getLinearTickPositions:function(a,b,c){var g,k=p(Math.floor(b/a)*a),e=p(Math.ceil(c/a)*a),B=[];if(b===c&&F(b))return[b];for(b=k;b<=e;){B.push(b);b=p(b+a);if(b===g)break;g=b}return B},getMinorTickPositions:function(){var a=this.options,b=this.tickPositions,c=this.minorTickInterval,k=[],e,m=this.pointRangePadding||0;e=this.min-m;var m=this.max+m,q=m-e;if(q&&q/c=this.minRange,q,d,r,f,n,w;this.isXAxis&&void 0===this.minRange&&!this.isLog&&(l(a.min)||l(a.max)?this.minRange=null:(c(this.series,function(a){f=a.xData;for(d=n=a.xIncrement? +1:f.length-1;0=J?(N=J,t=0):g.dataMax<=J&&(v=J,w=0)),g.min=A(C,N,g.dataMin),g.max=A(D,v,g.dataMax));q&&(!b&&0>= +Math.min(g.min,A(g.dataMin,g.min))&&a.error(10,1),g.min=p(d(g.min),15),g.max=p(d(g.max),15));g.range&&l(g.max)&&(g.userMin=g.min=C=Math.max(g.min,g.minFromRange()),g.userMax=D=g.max,g.range=null);y(g,"foundExtremes");g.beforePadding&&g.beforePadding();g.adjustForMinRange();!(K||g.axisPointRange||g.usePercentage||n)&&l(g.min)&&l(g.max)&&(d=g.max-g.min)&&(!l(C)&&t&&(g.min-=d*t),!l(D)&&w&&(g.max+=d*w));F(e.floor)?g.min=Math.max(g.min,e.floor):F(e.softMin)&&(g.min=Math.min(g.min,e.softMin));F(e.ceiling)? +g.max=Math.min(g.max,e.ceiling):F(e.softMax)&&(g.max=Math.max(g.max,e.softMax));u&&l(g.dataMin)&&(J=J||0,!l(C)&&g.min=J?g.min=J:!l(D)&&g.max>J&&g.dataMax<=J&&(g.max=J));g.tickInterval=g.min===g.max||void 0===g.min||void 0===g.max?1:n&&!z&&h===g.linkedParent.options.tickPixelInterval?z=g.linkedParent.tickInterval:A(z,this.tickAmount?(g.max-g.min)/Math.max(this.tickAmount-1,1):void 0,K?1:(g.max-g.min)*h/Math.max(g.len,h));f&&!b&&c(g.series,function(a){a.processData(g.min!==g.oldMin||g.max!== +g.oldMax)});g.setAxisTranslation(!0);g.beforeSetTickPositions&&g.beforeSetTickPositions();g.postProcessTickInterval&&(g.tickInterval=g.postProcessTickInterval(g.tickInterval));g.pointRange&&!z&&(g.tickInterval=Math.max(g.pointRange,g.tickInterval));b=A(e.minTickInterval,g.isDatetimeAxis&&g.closestPointRange);!z&&g.tickIntervalg.tickInterval&&1E3g.max)),!!this.tickAmount)); +this.tickAmount||(g.tickInterval=g.unsquish());this.setTickPositions()},setTickPositions:function(){var a=this.options,b,c=a.tickPositions,k=a.tickPositioner,e=a.startOnTick,m=a.endOnTick,q;this.tickmarkOffset=this.categories&&"between"===a.tickmarkPlacement&&1===this.tickInterval?.5:0;this.minorTickInterval="auto"===a.minorTickInterval&&this.tickInterval?this.tickInterval/5:a.minorTickInterval;this.tickPositions=b=c&&c.slice();!b&&(b=this.isDatetimeAxis?this.getTimeTicks(this.normalizeTimeTickInterval(this.tickInterval, +a.units),this.min,this.max,a.startOfWeek,this.ordinalPositions,this.closestPointRange,!0):this.isLog?this.getLogTickPositions(this.tickInterval,this.min,this.max):this.getLinearTickPositions(this.tickInterval,this.min,this.max),b.length>this.len&&(b=[b[0],b.pop()]),this.tickPositions=b,k&&(k=k.apply(this,[this.min,this.max])))&&(this.tickPositions=b=k);this.isLinked||(this.trimTicks(b,e,m),this.min===this.max&&l(this.min)&&!this.tickAmount&&(q=!0,this.min-=.5,this.max+=.5),this.single=q,c||k||this.adjustTickAmount())}, +trimTicks:function(a,b,c){var g=a[0],k=a[a.length-1],e=this.minPointOffset||0;if(b)this.min=g;else for(;this.min-e>a[0];)a.shift();if(c)this.max=k;else for(;this.max+eb&&(this.finalTickAmt=b,b=5);this.tickAmount=b},adjustTickAmount:function(){var a=this.tickInterval,b=this.tickPositions,c=this.tickAmount,k=this.finalTickAmt,e=b&&b.length;if(ec&&(this.tickInterval*=2,this.setTickPositions());if(l(k)){for(a=c=b.length;a--;)(3===k&&1===a%2||2>=k&&0k&&(a=k)),l(c)&&(bk&&(b=k))),this.displayBtn=void 0!==a||void 0!==b,this.setExtremes(a,b,!1,void 0,{trigger:"zoom"});return!0},setAxisSize:function(){var a=this.chart,b=this.options,c=b.offsetLeft||0,k=this.horiz,e=A(b.width,a.plotWidth-c+(b.offsetRight||0)),m=A(b.height,a.plotHeight),q=A(b.top,a.plotTop),b=A(b.left, +a.plotLeft+c),c=/%$/;c.test(m)&&(m=Math.round(parseFloat(m)/100*a.plotHeight));c.test(q)&&(q=Math.round(parseFloat(q)/100*a.plotHeight+a.plotTop));this.left=b;this.top=q;this.width=e;this.height=m;this.bottom=a.chartHeight-m-q;this.right=a.chartWidth-e-b;this.len=Math.max(k?e:m,0);this.pos=k?b:q},getExtremes:function(){var a=this.isLog,b=this.lin2log;return{min:a?p(b(this.min)):this.min,max:a?p(b(this.max)):this.max,dataMin:this.dataMin,dataMax:this.dataMax,userMin:this.userMin,userMax:this.userMax}}, +getThreshold:function(a){var b=this.isLog,g=this.lin2log,c=b?g(this.min):this.min,b=b?g(this.max):this.max;null===a?a=c:c>a?a=c:ba?"right":195a?"left":"center"},tickSize:function(a){var b=this.options,g=b[a+"Length"],c=A(b[a+"Width"],"tick"===a&&this.isXAxis?1:0);if(c&&g)return"inside"===b[a+"Position"]&&(g=-g),[g,c]},labelMetrics:function(){return this.chart.renderer.fontMetrics(this.options.labels.style&& +this.options.labels.style.fontSize,this.ticks[0]&&this.ticks[0].label)},unsquish:function(){var a=this.options.labels,b=this.horiz,k=this.tickInterval,e=k,m=this.len/(((this.categories?1:0)+this.max-this.min)/k),q,d=a.rotation,r=this.labelMetrics(),f,n=Number.MAX_VALUE,w,t=function(a){a/=m||1;a=1=a)f=t(Math.abs(r.h/Math.sin(u*a))),b=f+ +Math.abs(a/360),b(c.step||0)&&!c.rotation&&(this.staggerLines||1)*a.plotWidth/k||!b&&(e&&e-a.spacing[3]||.33*a.chartWidth)},renderUnsquish:function(){var a=this.chart,b=a.renderer,k=this.tickPositions,m=this.ticks,q=this.options.labels,d=this.horiz, +f=this.getSlotWidth(),n=Math.max(1,Math.round(f-2*(q.padding||5))),w={},t=this.labelMetrics(),z=q.style&&q.style.textOverflow,h,l=0,x,F;e(q.rotation)||(w.rotation=q.rotation||0);c(k,function(a){(a=m[a])&&a.labelLength>l&&(l=a.labelLength)});this.maxLabelLength=l;if(this.autoRotation)l>n&&l>t.h?w.rotation=this.labelRotation:this.labelRotation=0;else if(f&&(h={width:n+"px"},!z))for(h.textOverflow="clip",x=k.length;!d&&x--;)if(F=k[x],n=m[F].label)n.styles&&"ellipsis"===n.styles.textOverflow?n.css({textOverflow:"clip"}): +m[F].labelLength>f&&n.css({width:f+"px"}),n.getBBox().height>this.len/k.length-(t.h-t.f)&&(n.specCss={textOverflow:"ellipsis"});w.rotation&&(h={width:(l>.5*a.chartHeight?.33*a.chartHeight:a.chartHeight)+"px"},z||(h.textOverflow="ellipsis"));if(this.labelAlign=q.align||this.autoLabelAlign(this.labelRotation))w.align=this.labelAlign;c(k,function(a){var b=(a=m[a])&&a.label;b&&(b.attr(w),h&&b.css(r(h,b.specCss)),delete b.specCss,a.rotation=w.rotation)});this.tickRotCorr=b.rotCorr(t.b,this.labelRotation|| +0,0!==this.side)},hasData:function(){return this.hasVisibleSeries||l(this.min)&&l(this.max)&&!!this.tickPositions},addTitle:function(a){var b=this.chart.renderer,g=this.horiz,c=this.opposite,k=this.options.title,e;this.axisTitle||((e=k.textAlign)||(e=(g?{low:"left",middle:"center",high:"right"}:{low:c?"right":"left",middle:"center",high:c?"left":"right"})[k.align]),this.axisTitle=b.text(k.text,0,0,k.useHTML).attr({zIndex:7,rotation:k.rotation||0,align:e}).addClass("highcharts-axis-title").css(k.style).add(this.axisGroup), +this.axisTitle.isNew=!0);this.axisTitle[a?"show":"hide"](!0)},getOffset:function(){var a=this,b=a.chart,k=b.renderer,e=a.options,m=a.tickPositions,q=a.ticks,d=a.horiz,r=a.side,n=b.inverted?[1,0,3,2][r]:r,w,f,t=0,z,h=0,x=e.title,F=e.labels,p=0,K=b.axisOffset,b=b.clipOffset,J=[-1,1,1,-1][r],u,y=e.className,v=a.axisParent,C=this.tickSize("tick");w=a.hasData();a.showAxis=f=w||A(e.showEmpty,!0);a.staggerLines=a.horiz&&F.staggerLines;a.axisGroup||(a.gridGroup=k.g("grid").attr({zIndex:e.gridZIndex||1}).addClass("highcharts-"+ +this.coll.toLowerCase()+"-grid "+(y||"")).add(v),a.axisGroup=k.g("axis").attr({zIndex:e.zIndex||2}).addClass("highcharts-"+this.coll.toLowerCase()+" "+(y||"")).add(v),a.labelGroup=k.g("axis-labels").attr({zIndex:F.zIndex||7}).addClass("highcharts-"+a.coll.toLowerCase()+"-labels "+(y||"")).add(v));if(w||a.isLinked)c(m,function(b){q[b]?q[b].addLabel():q[b]=new N(a,b)}),a.renderUnsquish(),!1===F.reserveSpace||0!==r&&2!==r&&{1:"left",3:"right"}[r]!==a.labelAlign&&"center"!==a.labelAlign||c(m,function(a){p= +Math.max(q[a].getLabelSize(),p)}),a.staggerLines&&(p*=a.staggerLines,a.labelOffset=p*(a.opposite?-1:1));else for(u in q)q[u].destroy(),delete q[u];x&&x.text&&!1!==x.enabled&&(a.addTitle(f),f&&(t=a.axisTitle.getBBox()[d?"height":"width"],z=x.offset,h=l(z)?0:A(x.margin,d?5:10)));a.renderLine();a.offset=J*A(e.offset,K[r]);a.tickRotCorr=a.tickRotCorr||{x:0,y:0};k=0===r?-a.labelMetrics().h:2===r?a.tickRotCorr.y:0;h=Math.abs(p)+h;p&&(h=h-k+J*(d?A(F.y,a.tickRotCorr.y+8*J):F.x));a.axisTitleMargin=A(z,h); +K[r]=Math.max(K[r],a.axisTitleMargin+t+J*a.offset,h,w&&m.length&&C?C[0]:0);e=e.offset?0:2*Math.floor(a.axisLine.strokeWidth()/2);b[n]=Math.max(b[n],e)},getLinePath:function(a){var b=this.chart,c=this.opposite,g=this.offset,k=this.horiz,e=this.left+(c?this.width:0)+g,g=b.chartHeight-this.bottom-(c?this.height:0)+g;c&&(a*=-1);return b.renderer.crispLine(["M",k?this.left:e,k?g:this.top,"L",k?b.chartWidth-this.right:e,k?g:b.chartHeight-this.bottom],a)},renderLine:function(){this.axisLine||(this.axisLine= +this.chart.renderer.path().addClass("highcharts-axis-line").add(this.axisGroup),this.axisLine.attr({stroke:this.options.lineColor,"stroke-width":this.options.lineWidth,zIndex:7}))},getTitlePosition:function(){var a=this.horiz,b=this.left,c=this.top,k=this.len,e=this.options.title,m=a?b:c,q=this.opposite,d=this.offset,r=e.x||0,n=e.y||0,w=this.chart.renderer.fontMetrics(e.style&&e.style.fontSize,this.axisTitle).f,k={low:m+(a?0:k),middle:m+k/2,high:m+(a?k:0)}[e.align],b=(a?c+this.height:b)+(a?1:-1)* +(q?-1:1)*this.axisTitleMargin+(2===this.side?w:0);return{x:a?k+r:b+(q?this.width:0)+d+r,y:a?b+n-(q?this.height:0)+d:k+n}},render:function(){var a=this,b=a.chart,e=b.renderer,m=a.options,q=a.isLog,d=a.lin2log,r=a.isLinked,n=a.tickPositions,w=a.axisTitle,f=a.ticks,t=a.minorTicks,z=a.alternateBands,h=m.stackLabels,l=m.alternateGridColor,x=a.tickmarkOffset,p=a.axisLine,A=b.hasRendered&&F(a.oldMin),K=a.showAxis,u=C(e.globalAnimation),y,v;a.labelEdge.length=0;a.overlap=!1;c([f,t,z],function(a){for(var b in a)a[b].isActive= +!1});if(a.hasData()||r)a.minorTickInterval&&!a.categories&&c(a.getMinorTickPositions(),function(b){t[b]||(t[b]=new N(a,b,"minor"));A&&t[b].isNew&&t[b].render(null,!0);t[b].render(null,!1,1)}),n.length&&(c(n,function(b,c){if(!r||b>=a.min&&b<=a.max)f[b]||(f[b]=new N(a,b)),A&&f[b].isNew&&f[b].render(c,!0,.1),f[b].render(c)}),x&&(0===a.min||a.single)&&(f[-1]||(f[-1]=new N(a,-1,null,!0)),f[-1].render(-1))),l&&c(n,function(c,g){v=void 0!==n[g+1]?n[g+1]+x:a.max-x;0===g%2&&c=c.second?0:A*Math.floor(e.getMilliseconds()/A));if(x>=c.second)e[C.hcSetSeconds](x>=c.minute?0:A*Math.floor(e.getSeconds()/A));if(x>=c.minute)e[C.hcSetMinutes](x>=c.hour?0:A*Math.floor(e[C.hcGetMinutes]()/A));if(x>=c.hour)e[C.hcSetHours](x>=c.day?0:A*Math.floor(e[C.hcGetHours]()/A));if(x>=c.day)e[C.hcSetDate](x>=c.month?1:A*Math.floor(e[C.hcGetDate]()/A));x>=c.month&&(e[C.hcSetMonth](x>=c.year?0:A*Math.floor(e[C.hcGetMonth]()/A)),F=e[C.hcGetFullYear]()); +if(x>=c.year)e[C.hcSetFullYear](F-F%A);if(x===c.week)e[C.hcSetDate](e[C.hcGetDate]()-e[C.hcGetDay]()+d(m,1));F=e[C.hcGetFullYear]();m=e[C.hcGetMonth]();var w=e[C.hcGetDate](),K=e[C.hcGetHours]();if(C.hcTimezoneOffset||C.hcGetTimezoneOffset)k=(!n||!!C.hcGetTimezoneOffset)&&(t-y>4*c.month||l(y)!==l(t)),e=e.getTime(),e=new C(e+l(e));n=e.getTime();for(y=1;np&&(!l||q<=v)&&void 0!==q&&y.push(q),q>v&&(z=!0),q=b;else p=c(p),v=c(v),a=f[l?"minorTickInterval":"tickInterval"],a=h("auto"===a?null:a,this._minorAutoInterval,f.tickPixelInterval/(l?5:1)*(v-p)/((l?d/this.tickPositions.length:d)||1)),a=I(a,null,C(a)),y=G(this.getLinearTickPositions(a,p,v),n),l||(this._minorAutoInterval=a/5);l||(this.tickInterval=a);return y};D.prototype.log2lin= +function(a){return Math.log(a)/Math.LN10};D.prototype.lin2log=function(a){return Math.pow(10,a)}})(L);(function(a){var D=a.dateFormat,C=a.each,G=a.extend,I=a.format,h=a.isNumber,f=a.map,p=a.merge,v=a.pick,l=a.splat,u=a.syncTimeout,d=a.timeUnits;a.Tooltip=function(){this.init.apply(this,arguments)};a.Tooltip.prototype={init:function(a,d){this.chart=a;this.options=d;this.crosshairs=[];this.now={x:0,y:0};this.isHidden=!0;this.split=d.split&&!a.inverted;this.shared=d.shared||this.split},cleanSplit:function(a){C(this.chart.series, +function(c){var d=c&&c.tt;d&&(!d.isActive||a?c.tt=d.destroy():d.isActive=!1)})},getLabel:function(){var a=this.chart.renderer,d=this.options;this.label||(this.split?this.label=a.g("tooltip"):(this.label=a.label("",0,0,d.shape||"callout",null,null,d.useHTML,null,"tooltip").attr({padding:d.padding,r:d.borderRadius}),this.label.attr({fill:d.backgroundColor,"stroke-width":d.borderWidth}).css(d.style).shadow(d.shadow)),this.label.attr({zIndex:8}).add());return this.label},update:function(a){this.destroy(); +this.init(this.chart,p(!0,this.options,a))},destroy:function(){this.label&&(this.label=this.label.destroy());this.split&&this.tt&&(this.cleanSplit(this.chart,!0),this.tt=this.tt.destroy());clearTimeout(this.hideTimer);clearTimeout(this.tooltipTimeout)},move:function(a,d,f,t){var c=this,b=c.now,q=!1!==c.options.animation&&!c.isHidden&&(1n-q?n:n-q);else if(w)b[a]=Math.max(e,g+q+k>c?g:g+q);else return!1},p=function(a,c,k,g){var e;gc-m?e=!1:b[a]=gc-k/2?c-k-2:g-k/2;return e},k=function(a){var b=h;h=e;e=b;n=a},w=function(){!1!==l.apply(0,h)?!1!==p.apply(0,e)||n||(k(!0),w()):n?b.x=b.y=0:(k(!0), +w())};(c.inverted||1w&&(q=!1);a=(c.series&&c.series.yAxis&&c.series.yAxis.pos)+(c.plotY||0);a-=m.plotTop;n.push({target:c.isHeader? +m.plotHeight+l:a,rank:c.isHeader?1:0,size:r.tt.getBBox().height+1,point:c,x:w,tt:k})});this.cleanSplit();a.distribute(n,m.plotHeight+l);C(n,function(a){var b=a.point,c=b.series;a.tt.attr({visibility:void 0===a.pos?"hidden":"inherit",x:q||b.isHeader?a.x:b.plotX+m.plotLeft+v(h.distance,16),y:a.pos+m.plotTop,anchorX:b.isHeader?b.plotX+m.plotLeft:b.plotX+c.xAxis.pos,anchorY:b.isHeader?a.pos+m.plotTop-15:b.plotY+c.yAxis.pos})})},updatePosition:function(a){var c=this.chart,d=this.getLabel(),d=(this.options.positioner|| +this.getPosition).call(this,d.width,d.height,a);this.move(Math.round(d.x),Math.round(d.y||0),a.plotX+c.plotLeft,a.plotY+c.plotTop)},getXDateFormat:function(a,f,h){var c;f=f.dateTimeLabelFormats;var m=h&&h.closestPointRange,b,q={millisecond:15,second:12,minute:9,hour:6,day:3},n,l="millisecond";if(m){n=D("%m-%d %H:%M:%S.%L",a.x);for(b in d){if(m===d.week&&+D("%w",a.x)===h.options.startOfWeek&&"00:00:00.000"===n.substr(6)){b="week";break}if(d[b]>m){b=l;break}if(q[b]&&n.substr(q[b])!=="01-01 00:00:00.000".substr(q[b]))break; +"week"!==b&&(l=b)}b&&(c=f[b])}else c=f.day;return c||f.year},tooltipFooterHeaderFormatter:function(a,d){var c=d?"footer":"header";d=a.series;var f=d.tooltipOptions,m=f.xDateFormat,b=d.xAxis,q=b&&"datetime"===b.options.type&&h(a.key),c=f[c+"Format"];q&&!m&&(m=this.getXDateFormat(a,f,b));q&&m&&(c=c.replace("{point.key}","{point.key:"+m+"}"));return I(c,{point:a,series:d})},bodyFormatter:function(a){return f(a,function(a){var c=a.series.tooltipOptions;return(c.pointFormatter||a.point.tooltipFormatter).call(a.point, +c.pointFormat)})}}})(L);(function(a){var D=a.addEvent,C=a.attr,G=a.charts,I=a.color,h=a.css,f=a.defined,p=a.doc,v=a.each,l=a.extend,u=a.fireEvent,d=a.offset,c=a.pick,n=a.removeEvent,y=a.splat,t=a.Tooltip,m=a.win;a.Pointer=function(a,c){this.init(a,c)};a.Pointer.prototype={init:function(a,m){this.options=m;this.chart=a;this.runChartClick=m.chart.events&&!!m.chart.events.click;this.pinchDown=[];this.lastValidTouch={};t&&m.tooltip.enabled&&(a.tooltip=new t(a,m.tooltip),this.followTouchMove=c(m.tooltip.followTouchMove, +!0));this.setDOMEvents()},zoomOption:function(a){var b=this.chart,m=b.options.chart,d=m.zoomType||"",b=b.inverted;/touch/.test(a.type)&&(d=c(m.pinchType,d));this.zoomX=a=/x/.test(d);this.zoomY=d=/y/.test(d);this.zoomHor=a&&!b||d&&b;this.zoomVert=d&&!b||a&&b;this.hasZoom=a||d},normalize:function(a,c){var b,q;a=a||m.event;a.target||(a.target=a.srcElement);q=a.touches?a.touches.length?a.touches.item(0):a.changedTouches[0]:a;c||(this.chartPosition=c=d(this.chart.container));void 0===q.pageX?(b=Math.max(a.x, +a.clientX-c.left),c=a.y):(b=q.pageX-c.left,c=q.pageY-c.top);return l(a,{chartX:Math.round(b),chartY:Math.round(c)})},getCoordinates:function(a){var b={xAxis:[],yAxis:[]};v(this.chart.axes,function(c){b[c.isXAxis?"xAxis":"yAxis"].push({axis:c,value:c.toValue(a[c.horiz?"chartX":"chartY"])})});return b},runPointActions:function(b){var m=this.chart,d=m.series,f=m.tooltip,e=f?f.shared:!1,r=!0,n=m.hoverPoint,h=m.hoverSeries,k,w,l,t=[],u;if(!e&&!h)for(k=0;kb.series.index?-1:1}));if(e)for(k=t.length;k--;)(t[k].x!==t[0].x||t[k].series.noSharedTooltip)&& +t.splice(k,1);if(t[0]&&(t[0]!==this.prevKDPoint||f&&f.isHidden)){if(e&&!t[0].series.noSharedTooltip){for(k=0;kn+w&&(m=n+w),ek+h&&(e=k+h),this.hasDragged=Math.sqrt(Math.pow(g-m,2)+Math.pow(p-e,2)),10k.max&&(f=k.max-e,B=!0);B?(J-=.8*(J-n[m][0]),w||(g-=.8*(g-n[m][1])),h()):n[m]=[J, +g];A||(c[m]=r-p,c[l]=e);c=A?1/x:x;d[l]=e;d[m]=f;u[A?a?"scaleY":"scaleX":"scale"+b]=x;u["translate"+b]=c*p+(J-c*K)},pinch:function(a){var p=this,l=p.chart,u=p.pinchDown,d=a.touches,c=d.length,n=p.lastValidTouch,y=p.hasZoom,t=p.selectionMarker,m={},b=1===c&&(p.inClass(a.target,"highcharts-tracker")&&l.runTrackerClick||p.runChartClick),q={};1c-6&&h(p||b.chartWidth-2*k-B-m.x)&&(this.itemX=B,this.itemY+=g+this.lastLineHeight+y,this.lastLineHeight=0);this.maxItemWidth=Math.max(this.maxItemWidth,e);this.lastItemY=g+this.itemY+y;this.lastLineHeight=Math.max(h,this.lastLineHeight);a._legendItemPos=[this.itemX,this.itemY];f?this.itemX+=e: +(this.itemY+=g+h+y,this.lastLineHeight=h);this.offsetWidth=p||Math.max((f?this.itemX-B-w:e)+k,this.offsetWidth)},getAllItems:function(){var a=[];f(this.chart.series,function(b){var c=b&&b.options;b&&d(c.showInLegend,h(c.linkedTo)?!1:void 0,!0)&&(a=a.concat(b.legendItems||("point"===c.legendType?b.data:b)))});return a},adjustMargins:function(a,b){var c=this.chart,m=this.options,n=m.align.charAt(0)+m.verticalAlign.charAt(0)+m.layout.charAt(0);m.floating||f([/(lth|ct|rth)/,/(rtv|rm|rbv)/,/(rbh|cb|lbh)/, +/(lbv|lm|ltv)/],function(e,f){e.test(n)&&!h(a[f])&&(c[l[f]]=Math.max(c[l[f]],c.legend[(f+1)%2?"legendHeight":"legendWidth"]+[1,-1,-1,1][f]*m[f%2?"x":"y"]+d(m.margin,12)+b[f]))})},render:function(){var a=this,b=a.chart,c=b.renderer,d=a.group,h,e,r,l,t=a.box,k=a.options,w=a.padding;a.itemX=a.initialItemX;a.itemY=a.initialItemY;a.offsetWidth=0;a.lastItemY=0;d||(a.group=d=c.g("legend").attr({zIndex:7}).add(),a.contentGroup=c.g().attr({zIndex:1}).add(d),a.scrollGroup=c.g().add(a.contentGroup));a.renderTitle(); +h=a.getAllItems();n(h,function(a,b){return(a.options&&a.options.legendIndex||0)-(b.options&&b.options.legendIndex||0)});k.reversed&&h.reverse();a.allItems=h;a.display=e=!!h.length;a.lastLineHeight=0;f(h,function(b){a.renderItem(b)});r=(k.width||a.offsetWidth)+w;l=a.lastItemY+a.lastLineHeight+a.titleHeight;l=a.handleOverflow(l);l+=w;t||(a.box=t=c.rect().addClass("highcharts-legend-box").attr({r:k.borderRadius}).add(d),t.isNew=!0);t.attr({stroke:k.borderColor,"stroke-width":k.borderWidth||0,fill:k.backgroundColor|| +"none"}).shadow(k.shadow);0c&&!1!==t.enabled?(this.clipHeight=n=Math.max(c-20-this.titleHeight-y,0),this.currentPage=d(this.currentPage,1),this.fullHeight= +a,f(B,function(a,b){var c=a._legendItemPos[1];a=Math.round(a.legendItem.getBBox().height);var k=u.length;if(!k||c-u[k-1]>n&&(g||c)!==u[k-1])u.push(g||c),k++;b===B.length-1&&c+a-u[k-1]>n&&u.push(c);c!==g&&(g=c)}),l||(l=b.clipRect=m.clipRect(0,y,9999,0),b.contentGroup.clip(l)),v(n),p||(this.nav=p=m.g().attr({zIndex:1}).add(this.group),this.up=m.symbol("triangle",0,0,w,w).on("click",function(){b.scroll(-1,k)}).add(p),this.pager=m.text("",15,10).addClass("highcharts-legend-navigation").css(t.style).add(p), +this.down=m.symbol("triangle-down",0,0,w,w).on("click",function(){b.scroll(1,k)}).add(p)),b.scroll(0),a=c):p&&(v(),p.hide(),this.scrollGroup.attr({translateY:1}),this.clipHeight=0);return a},scroll:function(a,b){var d=this.pages,f=d.length;a=this.currentPage+a;var m=this.clipHeight,e=this.options.navigation,h=this.pager,n=this.padding;a>f&&(a=f);0m&&(d=typeof a[0],"string"===d?c.name=a[0]:"number"===d&&(c.x=a[0]),b++);l=h.value;)h=c[++f];h&&h.color&&!this.options.color&&(this.color=h.color);return h},destroy:function(){var a=this.series.chart,c=a.hoverPoints,f;a.pointCount--;c&&(this.setState(),I(c,this),c.length||(a.hoverPoints=null));if(this===a.hoverPoint)this.onMouseOut();if(this.graphic||this.dataLabel)u(this),this.destroyElements();this.legendItem&&a.legend.destroyItem(this);for(f in this)this[f]=null},destroyElements:function(){for(var a= +["graphic","dataLabel","dataLabelUpper","connector","shadowGroup"],c,f=6;f--;)c=a[f],this[c]&&(this[c]=this[c].destroy())},getLabelConfig:function(){return{x:this.category,y:this.y,color:this.color,key:this.name||this.category,series:this.series,point:this,percentage:this.percentage,total:this.total||this.stackTotal}},tooltipFormatter:function(a){var c=this.series,d=c.tooltipOptions,h=l(d.valueDecimals,""),t=d.valuePrefix||"",m=d.valueSuffix||"";C(c.pointArrayMap||["y"],function(b){b="{point."+b; +if(t||m)a=a.replace(b+"}",t+b+"}"+m);a=a.replace(b+"}",b+":,."+h+"f}")});return f(a,{point:this,series:this.series})},firePointEvent:function(a,c,f){var d=this,n=this.series.options;(n.point.events[a]||d.options&&d.options.events&&d.options.events[a])&&this.importEvents();"click"===a&&n.allowPointSelect&&(f=function(a){d.select&&d.select(null,a.ctrlKey||a.metaKey||a.shiftKey)});h(this,a,c,f)},visible:!0}})(L);(function(a){var D=a.addEvent,C=a.animObject,G=a.arrayMax,I=a.arrayMin,h=a.correctFloat, +f=a.Date,p=a.defaultOptions,v=a.defaultPlotOptions,l=a.defined,u=a.each,d=a.erase,c=a.extend,n=a.fireEvent,y=a.grep,t=a.isArray,m=a.isNumber,b=a.isString,q=a.merge,z=a.pick,F=a.removeEvent,e=a.splat,r=a.SVGElement,x=a.syncTimeout,A=a.win;a.Series=a.seriesType("line",null,{lineWidth:2,allowPointSelect:!1,showCheckbox:!1,animation:{duration:1E3},events:{},marker:{lineWidth:0,lineColor:"#ffffff",radius:4,states:{hover:{animation:{duration:50},enabled:!0,radiusPlus:2,lineWidthPlus:1},select:{fillColor:"#cccccc", +lineColor:"#000000",lineWidth:2}}},point:{events:{}},dataLabels:{align:"center",formatter:function(){return null===this.y?"":a.numberFormat(this.y,-1)},style:{fontSize:"11px",fontWeight:"bold",color:"contrast",textOutline:"1px contrast"},verticalAlign:"bottom",x:0,y:0,padding:5},cropThreshold:300,pointRange:0,softThreshold:!0,states:{hover:{lineWidthPlus:1,marker:{},halo:{size:10,opacity:.25}},select:{marker:{}}},stickyTracking:!0,turboThreshold:1E3},{isCartesian:!0,pointClass:a.Point,sorted:!0,requireSorting:!0, +directTouch:!1,axisTypes:["xAxis","yAxis"],colorCounter:0,parallelArrays:["x","y"],coll:"series",init:function(a,b){var k=this,e,d,g=a.series,f;k.chart=a;k.options=b=k.setOptions(b);k.linkedSeries=[];k.bindAxes();c(k,{name:b.name,state:"",visible:!1!==b.visible,selected:!0===b.selected});d=b.events;for(e in d)D(k,e,d[e]);if(d&&d.click||b.point&&b.point.events&&b.point.events.click||b.allowPointSelect)a.runTrackerClick=!0;k.getColor();k.getSymbol();u(k.parallelArrays,function(a){k[a+"Data"]=[]});k.setData(b.data, +!1);k.isCartesian&&(a.hasCartesianSeries=!0);g.length&&(f=g[g.length-1]);k._i=z(f&&f._i,-1)+1;for(a=this.insert(g);a=z(a[c].options.index,a[c]._i)){a.splice(c+1,0,this);break}-1===c&&a.unshift(this);c+=1}else a.push(this);return z(c,a.length-1)},bindAxes:function(){var b=this,c=b.options,e=b.chart,d;u(b.axisTypes||[],function(k){u(e[k],function(a){d= +a.options;if(c[k]===d.index||void 0!==c[k]&&c[k]===d.id||void 0===c[k]&&0===d.index)b.insert(a.series),b[k]=a,a.isDirty=!0});b[k]||b.optionalAxis===k||a.error(18,!0)})},updateParallelArrays:function(a,b){var c=a.series,k=arguments,e=m(b)?function(g){var k="y"===g&&c.toYData?c.toYData(a):a[g];c[g+"Data"][b]=k}:function(a){Array.prototype[b].apply(c[a+"Data"],Array.prototype.slice.call(k,2))};u(c.parallelArrays,e)},autoIncrement:function(){var a=this.options,b=this.xIncrement,c,e=a.pointIntervalUnit, +b=z(b,a.pointStart,0);this.pointInterval=c=z(this.pointInterval,a.pointInterval,1);e&&(a=new f(b),"day"===e?a=+a[f.hcSetDate](a[f.hcGetDate]()+c):"month"===e?a=+a[f.hcSetMonth](a[f.hcGetMonth]()+c):"year"===e&&(a=+a[f.hcSetFullYear](a[f.hcGetFullYear]()+c)),c=a-b);this.xIncrement=b+c;return b},setOptions:function(a){var b=this.chart,c=b.options.plotOptions,b=b.userOptions||{},k=b.plotOptions||{},e=c[this.type];this.userOptions=a;c=q(e,c.series,a);this.tooltipOptions=q(p.tooltip,p.plotOptions[this.type].tooltip, +b.tooltip,k.series&&k.series.tooltip,k[this.type]&&k[this.type].tooltip,a.tooltip);null===e.marker&&delete c.marker;this.zoneAxis=c.zoneAxis;a=this.zones=(c.zones||[]).slice();!c.negativeColor&&!c.negativeFillColor||c.zones||a.push({value:c[this.zoneAxis+"Threshold"]||c.threshold||0,className:"highcharts-negative",color:c.negativeColor,fillColor:c.negativeFillColor});a.length&&l(a[a.length-1].value)&&a.push({color:this.color,fillColor:this.fillColor});return c},getCyclic:function(a,b,c){var k,e=this.userOptions, +g=a+"Index",d=a+"Counter",f=c?c.length:z(this.chart.options.chart[a+"Count"],this.chart[a+"Count"]);b||(k=z(e[g],e["_"+g]),l(k)||(e["_"+g]=k=this.chart[d]%f,this.chart[d]+=1),c&&(b=c[k]));void 0!==k&&(this[g]=k);this[a]=b},getColor:function(){this.options.colorByPoint?this.options.color=null:this.getCyclic("color",this.options.color||v[this.type].color,this.chart.options.colors)},getSymbol:function(){this.getCyclic("symbol",this.options.marker.symbol,this.chart.options.symbols)},drawLegendSymbol:a.LegendSymbolMixin.drawLineMarker, +setData:function(c,e,d,f){var k=this,g=k.points,h=g&&g.length||0,n,r=k.options,w=k.chart,l=null,q=k.xAxis,p=r.turboThreshold,x=this.xData,A=this.yData,F=(n=k.pointArrayMap)&&n.length;c=c||[];n=c.length;e=z(e,!0);if(!1!==f&&n&&h===n&&!k.cropped&&!k.hasGroupedData&&k.visible)u(c,function(a,b){g[b].update&&a!==r.data[b]&&g[b].update(a,!1,null,!1)});else{k.xIncrement=null;k.colorCounter=0;u(this.parallelArrays,function(a){k[a+"Data"].length=0});if(p&&n>p){for(d=0;null===l&&dh||this.forceCrop))if(c[e-1]p)c=[], +k=[];else if(c[0]p)d=this.cropData(this.xData,this.yData,t,p),c=d.xData,k=d.yData,d=d.start,g=!0;for(h=c.length||1;--h;)e=q?n(c[h])-n(c[h-1]):c[h]-c[h-1],0e&&this.requireSorting&&a.error(15);this.cropped=g;this.cropStart=d;this.processedXData=c;this.processedYData=k;this.closestPointRange=f},cropData:function(a,b,c,e){var k=a.length,g=0,d=k,f=z(this.cropShoulder,1),h;for(h=0;h=c){g=Math.max(0,h-f);break}for(c=h;ce){d=c+f;break}return{xData:a.slice(g, +d),yData:b.slice(g,d),start:g,end:d}},generatePoints:function(){var a=this.options.data,b=this.data,c,d=this.processedXData,f=this.processedYData,g=this.pointClass,h=d.length,m=this.cropStart||0,n,r=this.hasGroupedData,l,q=[],t;b||r||(b=[],b.length=a.length,b=this.data=b);for(t=0;t=d&&(c[r-1]||n)<=f,h&&n)if(h=l.length)for(;h--;)null!==l[h]&&(k[g++]= +l[h]);else k[g++]=l;this.dataMin=I(k);this.dataMax=G(k)},translate:function(){this.processedXData||this.processData();this.generatePoints();var a=this.options,b=a.stacking,c=this.xAxis,e=c.categories,d=this.yAxis,g=this.points,f=g.length,n=!!this.modifyValue,r=a.pointPlacement,t="between"===r||m(r),q=a.threshold,p=a.startFromThreshold?q:0,x,u,A,F,v=Number.MAX_VALUE;"between"===r&&(r=.5);m(r)&&(r*=z(a.pointRange||c.pointRange));for(a=0;a=D&&(y.isNull=!0);y.plotX=x=h(Math.min(Math.max(-1E5,c.translate(C,0,0,0,1,r,"flags"===this.type)),1E5));b&&this.visible&&!y.isNull&&G&&G[C]&&(F=this.getStackIndicator(F,C,this.index),I=G[C],D=I.points[F.key],u=D[0],D=D[1],u===p&&F.key===G[C].base&&(u=z(q,d.min)),d.isLog&&0>=u&&(u=null),y.total=y.stackTotal=I.total,y.percentage=I.total&&y.y/I.total*100,y.stackY=D,I.setOffset(this.pointXOffset||0,this.barW||0));y.yBottom=l(u)?d.translate(u,0, +1,0,1):null;n&&(D=this.modifyValue(D,y));y.plotY=u="number"===typeof D&&Infinity!==D?Math.min(Math.max(-1E5,d.translate(D,0,1,0,1)),1E5):void 0;y.isInside=void 0!==u&&0<=u&&u<=d.len&&0<=x&&x<=c.len;y.clientX=t?h(c.translate(C,0,0,0,1,r)):x;y.negative=y.y<(q||0);y.category=e&&void 0!==e[y.x]?e[y.x]:y.x;y.isNull||(void 0!==A&&(v=Math.min(v,Math.abs(x-A))),A=x);y.zone=this.zones.length&&y.getZone()}this.closestPointRangePx=v},getValidPoints:function(a,b){var c=this.chart;return y(a||this.points||[], +function(a){return b&&!c.isInsidePlot(a.plotX,a.plotY,c.inverted)?!1:!a.isNull})},setClip:function(a){var b=this.chart,c=this.options,e=b.renderer,k=b.inverted,g=this.clipBox,d=g||b.clipBox,f=this.sharedClipKey||["_sharedClip",a&&a.duration,a&&a.easing,d.height,c.xAxis,c.yAxis].join(),h=b[f],m=b[f+"m"];h||(a&&(d.width=0,b[f+"m"]=m=e.clipRect(-99,k?-b.plotLeft:-b.plotTop,99,k?b.chartWidth:b.chartHeight)),b[f]=h=e.clipRect(d),h.count={length:0});a&&!h.count[this.index]&&(h.count[this.index]=!0,h.count.length+= +1);!1!==c.clip&&(this.group.clip(a||g?h:b.clipRect),this.markerGroup.clip(m),this.sharedClipKey=f);a||(h.count[this.index]&&(delete h.count[this.index],--h.count.length),0===h.count.length&&f&&b[f]&&(g||(b[f]=b[f].destroy()),b[f+"m"]&&(b[f+"m"]=b[f+"m"].destroy())))},animate:function(a){var b=this.chart,c=C(this.options.animation),e;a?this.setClip(c):(e=this.sharedClipKey,(a=b[e])&&a.animate({width:b.plotSizeX},c),b[e+"m"]&&b[e+"m"].animate({width:b.plotSizeX+99},c),this.animate=null)},afterAnimate:function(){this.setClip(); +n(this,"afterAnimate")},drawPoints:function(){var a=this.points,b=this.chart,c,e,d,g,f=this.options.marker,h,n,r,l,t=this.markerGroup,q=z(f.enabled,this.xAxis.isRadial?!0:null,this.closestPointRangePx>2*f.radius);if(!1!==f.enabled||this._hasPointMarkers)for(e=a.length;e--;)d=a[e],c=d.plotY,g=d.graphic,h=d.marker||{},n=!!d.marker,r=q&&void 0===h.enabled||h.enabled,l=d.isInside,r&&m(c)&&null!==d.y?(c=z(h.symbol,this.symbol),d.hasImage=0===c.indexOf("url"),r=this.markerAttribs(d,d.selected&&"select"), +g?g[l?"show":"hide"](!0).animate(r):l&&(0g&&b.shadow));d&&(d.startX=c.xMap,d.isArea=c.isArea)})},applyZones:function(){var a=this,b=this.chart,c=b.renderer,e=this.zones,d,g,f=this.clips||[], +h,m=this.graph,n=this.area,r=Math.max(b.chartWidth,b.chartHeight),l=this[(this.zoneAxis||"y")+"Axis"],q,t,p=b.inverted,x,A,F,y,v=!1;e.length&&(m||n)&&l&&void 0!==l.min&&(t=l.reversed,x=l.horiz,m&&m.hide(),n&&n.hide(),q=l.getExtremes(),u(e,function(e,k){d=t?x?b.plotWidth:0:x?0:l.toPixels(q.min);d=Math.min(Math.max(z(g,d),0),r);g=Math.min(Math.max(Math.round(l.toPixels(z(e.value,q.max),!0)),0),r);v&&(d=g=l.toPixels(q.max));A=Math.abs(d-g);F=Math.min(d,g);y=Math.max(d,g);l.isXAxis?(h={x:p?y:F,y:0,width:A, +height:r},x||(h.x=b.plotHeight-h.x)):(h={x:0,y:p?y:F,width:r,height:A},x&&(h.y=b.plotWidth-h.y));p&&c.isVML&&(h=l.isXAxis?{x:0,y:t?F:y,height:h.width,width:b.chartWidth}:{x:h.y-b.plotLeft-b.spacingBox.x,y:0,width:h.height,height:b.chartHeight});f[k]?f[k].animate(h):(f[k]=c.clipRect(h),m&&a["zone-graph-"+k].clip(f[k]),n&&a["zone-area-"+k].clip(f[k]));v=e.value>q.max}),this.clips=f)},invertGroups:function(a){function b(){var b={width:c.yAxis.len,height:c.xAxis.len};u(["group","markerGroup"],function(e){c[e]&& +c[e].attr(b).invert(a)})}var c=this,e;c.xAxis&&(e=D(c.chart,"resize",b),D(c,"destroy",e),b(a),c.invertGroups=b)},plotGroup:function(a,b,c,e,d){var g=this[a],k=!g;k&&(this[a]=g=this.chart.renderer.g(b).attr({zIndex:e||.1}).add(d),g.addClass("highcharts-series-"+this.index+" highcharts-"+this.type+"-series highcharts-color-"+this.colorIndex+" "+(this.options.className||"")));g.attr({visibility:c})[k?"attr":"animate"](this.getPlotBox());return g},getPlotBox:function(){var a=this.chart,b=this.xAxis,c= +this.yAxis;a.inverted&&(b=c,c=this.xAxis);return{translateX:b?b.left:a.plotLeft,translateY:c?c.top:a.plotTop,scaleX:1,scaleY:1}},render:function(){var a=this,b=a.chart,c,e=a.options,d=!!a.animate&&b.renderer.isSVG&&C(e.animation).duration,g=a.visible?"inherit":"hidden",f=e.zIndex,h=a.hasRendered,m=b.seriesGroup,n=b.inverted;c=a.plotGroup("group","series",g,f,m);a.markerGroup=a.plotGroup("markerGroup","markers",g,f,m);d&&a.animate(!0);c.inverted=a.isCartesian?n:!1;a.drawGraph&&(a.drawGraph(),a.applyZones()); +a.drawDataLabels&&a.drawDataLabels();a.visible&&a.drawPoints();a.drawTracker&&!1!==a.options.enableMouseTracking&&a.drawTracker();a.invertGroups(n);!1===e.clip||a.sharedClipKey||h||c.clip(b.clipRect);d&&a.animate();h||(a.animationTimeout=x(function(){a.afterAnimate()},d));a.isDirty=a.isDirtyData=!1;a.hasRendered=!0},redraw:function(){var a=this.chart,b=this.isDirty||this.isDirtyData,c=this.group,e=this.xAxis,d=this.yAxis;c&&(a.inverted&&c.attr({width:a.plotWidth,height:a.plotHeight}),c.animate({translateX:z(e&& +e.left,a.plotLeft),translateY:z(d&&d.top,a.plotTop)}));this.translate();this.render();b&&delete this.kdTree},kdDimensions:1,kdAxisArray:["clientX","plotY"],searchPoint:function(a,b){var c=this.xAxis,e=this.yAxis,d=this.chart.inverted;return this.searchKDTree({clientX:d?c.len-a.chartY+c.pos:a.chartX-c.pos,plotY:d?e.len-a.chartX+e.pos:a.chartY-e.pos},b)},buildKDTree:function(){function a(c,e,g){var d,k;if(k=c&&c.length)return d=b.kdAxisArray[e%g],c.sort(function(a,b){return a[d]-b[d]}),k=Math.floor(k/ +2),{point:c[k],left:a(c.slice(0,k),e+1,g),right:a(c.slice(k+1),e+1,g)}}var b=this,c=b.kdDimensions;delete b.kdTree;x(function(){b.kdTree=a(b.getValidPoints(null,!b.directTouch),c,c)},b.options.kdNow?0:1)},searchKDTree:function(a,b){function c(a,b,f,h){var m=b.point,n=e.kdAxisArray[f%h],r,q,t=m;q=l(a[d])&&l(m[d])?Math.pow(a[d]-m[d],2):null;r=l(a[g])&&l(m[g])?Math.pow(a[g]-m[g],2):null;r=(q||0)+(r||0);m.dist=l(r)?Math.sqrt(r):Number.MAX_VALUE;m.distX=l(q)?Math.sqrt(q):Number.MAX_VALUE;n=a[n]-m[n];r= +0>n?"left":"right";q=0>n?"right":"left";b[r]&&(r=c(a,b[r],f+1,h),t=r[k]p;)q--;this.updateParallelArrays(g,"splice",q,0,0);this.updateParallelArrays(g,q);m&&g.name&&(m[p]=g.name);n.splice(q,0,a);l&&(this.data.splice(q,0,null),this.processData());"point"===e.legendType&&this.generatePoints();c&&(f[0]&&f[0].remove? +f[0].remove(!1):(f.shift(),this.updateParallelArrays(g,"shift"),n.shift()));this.isDirtyData=this.isDirty=!0;b&&h.redraw(d)},removePoint:function(a,b,c){var e=this,d=e.data,f=d[a],h=e.points,m=e.chart,n=function(){h&&h.length===d.length&&h.splice(a,1);d.splice(a,1);e.options.data.splice(a,1);e.updateParallelArrays(f||{series:e},"splice",a,1);f&&f.destroy();e.isDirty=!0;e.isDirtyData=!0;b&&m.redraw()};z(c,m);b=t(b,!0);f?f.firePointEvent("remove",null,n):n()},remove:function(a,b,c){function e(){d.destroy(); +f.isDirtyLegend=f.isDirtyBox=!0;f.linkSeries();t(a,!0)&&f.redraw(b)}var d=this,f=d.chart;!1!==c?u(d,"remove",null,e):e()},update:function(a,b){var c=this,e=this.chart,d=this.userOptions,f=this.type,h=a.type||d.type||e.options.chart.type,m=q[f].prototype,n=["group","markerGroup","dataLabelsGroup"],g;if(h&&h!==f||void 0!==a.zIndex)n.length=0;p(n,function(a){n[a]=c[a];delete c[a]});a=y(d,{animation:!1,index:this.index,pointStart:this.xData[0]},{data:this.options.data},a);this.remove(!1,null,!1);for(g in m)this[g]= +void 0;l(this,q[h||f].prototype);p(n,function(a){c[a]=n[a]});this.init(e,a);e.linkSeries();t(b,!0)&&e.redraw(!1)}});l(G.prototype,{update:function(a,b){var c=this.chart;a=c.options[this.coll][this.options.index]=y(this.userOptions,a);this.destroy(!0);this.init(c,l(a,{events:void 0}));c.isDirtyBox=!0;t(b,!0)&&c.redraw()},remove:function(a){for(var b=this.chart,c=this.coll,e=this.series,d=e.length;d--;)e[d]&&e[d].remove(!1);v(b.axes,this);v(b[c],this);b.options[c].splice(this.options.index,1);p(b[c], +function(a,b){a.options.index=b});this.destroy();b.isDirtyBox=!0;t(a,!0)&&b.redraw()},setTitle:function(a,b){this.update({title:a},b)},setCategories:function(a,b){this.update({categories:a},b)}})})(L);(function(a){var D=a.color,C=a.each,G=a.map,I=a.pick,h=a.Series,f=a.seriesType;f("area","line",{softThreshold:!1,threshold:0},{singleStacks:!1,getStackPoints:function(){var a=[],f=[],h=this.xAxis,u=this.yAxis,d=u.stacks[this.stackKey],c={},n=this.points,y=this.index,t=u.series,m=t.length,b,q=I(u.options.reversedStacks, +!0)?1:-1,z,F;if(this.options.stacking){for(z=0;za&&l>f?(l=Math.max(a,f),d=2*f-l):lI&&d>f?(d=Math.max(I,f),l=2*f-d):d=Math.abs(c)&&.5a.closestPointRange*a.xAxis.transA,h=a.borderWidth=p(f.borderWidth,h?0:1),l=a.yAxis,m=a.translatedThreshold=l.getThreshold(f.threshold),b=p(f.minPointLength, +5),q=a.getColumnMetrics(),u=q.width,F=a.barW=Math.max(u,1+2*h),e=a.pointXOffset=q.offset;c.inverted&&(m-=.5);f.pointPadding&&(F=Math.ceil(F));v.prototype.translate.apply(a);G(a.points,function(d){var f=p(d.yBottom,m),h=999+Math.abs(f),h=Math.min(Math.max(-h,d.plotY),l.len+h),k=d.plotX+e,n=F,q=Math.min(h,f),r,t=Math.max(h,f)-q;Math.abs(t)b?f-b:m-(r?b:0));d.barX=k;d.pointWidth=u;d.tooltipPos=c.inverted?[l.len+l.pos-c.plotLeft- +h,a.xAxis.len-k-n/2,t]:[k+n/2,h+l.pos-c.plotTop,t];d.shapeType="rect";d.shapeArgs=a.crispCol.apply(a,d.isNull?[d.plotX,l.len/2,0,0]:[k,q,n,t])})},getSymbol:a.noop,drawLegendSymbol:a.LegendSymbolMixin.drawRectangle,drawGraph:function(){this.group[this.dense?"addClass":"removeClass"]("highcharts-dense-data")},pointAttribs:function(a,c){var d=this.options,f,h=this.pointAttrToOptions||{};f=h.stroke||"borderColor";var m=h["stroke-width"]||"borderWidth",b=a&&a.color||this.color,l=a[f]||d[f]||this.color|| +b,p=a[m]||d[m]||this[m]||0,h=d.dashStyle;a&&this.zones.length&&(b=(b=a.getZone())&&b.color||a.options.color||this.color);c&&(a=d.states[c],c=a.brightness,b=a.color||void 0!==c&&C(b).brighten(a.brightness).get()||b,l=a[f]||l,p=a[m]||p,h=a.dashStyle||h);f={fill:b,stroke:l,"stroke-width":p};d.borderRadius&&(f.r=d.borderRadius);h&&(f.dashstyle=h);return f},drawPoints:function(){var a=this,c=this.chart,l=a.options,p=c.renderer,t=l.animationLimit||250,m;G(a.points,function(b){var d=b.graphic;if(h(b.plotY)&& +null!==b.y){m=b.shapeArgs;if(d)d[c.pointCountl;++l)u=p[l],a=2>l||2===l&&/%$/.test(u),p[l]=C(u,[f,I,v,p[2]][l])+(a?h:0);p[3]>p[2]&&(p[3]=p[2]);return p}}})(L);(function(a){var D=a.addEvent,C=a.defined,G=a.each,I=a.extend,h=a.inArray,f=a.noop,p=a.pick,v=a.Point,l=a.Series,u=a.seriesType,d=a.setAnimation;u("pie","line",{center:[null,null],clip:!1,colorByPoint:!0,dataLabels:{distance:30,enabled:!0,formatter:function(){return null===this.y? +void 0:this.point.name},x:0},ignoreHiddenPoint:!0,legendType:"point",marker:null,size:null,showInLegend:!1,slicedOffset:10,stickyTracking:!1,tooltip:{followPointer:!0},borderColor:"#ffffff",borderWidth:1,states:{hover:{brightness:.1,shadow:!1}}},{isCartesian:!1,requireSorting:!1,directTouch:!0,noSharedTooltip:!0,trackerGroups:["group","dataLabelsGroup"],axisTypes:[],pointAttribs:a.seriesTypes.column.prototype.pointAttribs,animate:function(a){var c=this,d=c.points,f=c.startAngleRad;a||(G(d,function(a){var b= +a.graphic,d=a.shapeArgs;b&&(b.attr({r:a.startR||c.center[3]/2,start:f,end:f}),b.animate({r:d.r,start:d.start,end:d.end},c.options.animation))}),c.animate=null)},updateTotals:function(){var a,d=0,f=this.points,h=f.length,m,b=this.options.ignoreHiddenPoint;for(a=0;am.y&&(m.y=null),d+=b&&!m.visible?0:m.y;this.total=d;for(a=0;a1.5*Math.PI?u-=2*Math.PI:u<-Math.PI/2&&(u+=2*Math.PI);w.slicedTranslation={translateX:Math.round(Math.cos(u)*f),translateY:Math.round(Math.sin(u)*f)};b=Math.cos(u)*a[2]/2;l=Math.sin(u)*a[2]/2;w.tooltipPos=[a[0]+.7*b,a[1]+.7*l];w.half=u<-Math.PI/2||u>Math.PI/2?1:0;w.angle=u;h=Math.min(h,x/5);w.labelPos=[a[0]+b+Math.cos(u)*x,a[1]+l+Math.sin(u)*x,a[0]+b+Math.cos(u)*h,a[1]+l+Math.sin(u)* +h,a[0]+b,a[1]+l,0>x?"center":w.half?"right":"left",u]}},drawGraph:null,drawPoints:function(){var a=this,d=a.chart.renderer,f,h,m,b,l=a.options.shadow;l&&!a.shadowGroup&&(a.shadowGroup=d.g("shadow").add(a.group));G(a.points,function(c){if(null!==c.y){h=c.graphic;b=c.shapeArgs;f=c.sliced?c.slicedTranslation:{};var n=c.shadowGroup;l&&!n&&(n=c.shadowGroup=d.g("shadow").add(a.shadowGroup));n&&n.attr(f);m=a.pointAttribs(c,c.selected&&"select");h?h.setRadialReference(a.center).attr(m).animate(I(b,f)):(c.graphic= +h=d[c.shapeType](b).addClass(c.getClassName()).setRadialReference(a.center).attr(f).add(a.group),c.visible||h.attr({visibility:"hidden"}),h.attr(m).attr({"stroke-linejoin":"round"}).shadow(l,n))}})},searchPoint:f,sortByAngle:function(a,d){a.sort(function(a,c){return void 0!==a.angle&&(c.angle-a.angle)*d})},drawLegendSymbol:a.LegendSymbolMixin.drawRectangle,getCenter:a.CenteredSeriesMixin.getCenter,getSymbol:f},{init:function(){v.prototype.init.apply(this,arguments);var a=this,d;a.name=p(a.name,"Slice"); +d=function(c){a.slice("select"===c.type)};D(a,"select",d);D(a,"unselect",d);return a},setVisible:function(a,d){var c=this,f=c.series,m=f.chart,b=f.options.ignoreHiddenPoint;d=p(d,b);a!==c.visible&&(c.visible=c.options.visible=a=void 0===a?!c.visible:a,f.options.data[h(c,f.data)]=c.options,G(["graphic","dataLabel","connector","shadowGroup"],function(b){if(c[b])c[b][a?"show":"hide"](!0)}),c.legendItem&&m.legend.colorizeItem(c,a),a||"hover"!==c.state||c.setState(""),b&&(f.isDirty=!0),d&&m.redraw())}, +slice:function(a,f,l){var c=this.series;d(l,c.chart);p(f,!0);this.sliced=this.options.sliced=a=C(a)?a:!this.sliced;c.options.data[h(this,c.data)]=this.options;a=a?this.slicedTranslation:{translateX:0,translateY:0};this.graphic.animate(a);this.shadowGroup&&this.shadowGroup.animate(a)},haloPath:function(a){var c=this.shapeArgs;return this.sliced||!this.visible?[]:this.series.chart.renderer.symbols.arc(c.x,c.y,c.r+a,c.r+a,{innerR:this.shapeArgs.r,start:c.start,end:c.end})}})})(L);(function(a){var D= +a.addEvent,C=a.arrayMax,G=a.defined,I=a.each,h=a.extend,f=a.format,p=a.map,v=a.merge,l=a.noop,u=a.pick,d=a.relativeLength,c=a.Series,n=a.seriesTypes,y=a.stableSort;a.distribute=function(a,c){function b(a,b){return a.target-b.target}var d,f=!0,h=a,e=[],m;m=0;for(d=a.length;d--;)m+=a[d].size;if(m>c){y(a,function(a,b){return(b.rank||0)-(a.rank||0)});for(m=d=0;m<=c;)m+=a[d].size,d++;e=a.splice(d-1,a.length)}y(a,b);for(a=p(a,function(a){return{size:a.size,targets:[a.target]}});f;){for(d=a.length;d--;)f= +a[d],m=(Math.min.apply(0,f.targets)+Math.max.apply(0,f.targets))/2,f.pos=Math.min(Math.max(0,m-f.size/2),c-f.size);d=a.length;for(f=!1;d--;)0a[d].pos&&(a[d-1].size+=a[d].size,a[d-1].targets=a[d-1].targets.concat(a[d].targets),a[d-1].pos+a[d-1].size>c&&(a[d-1].pos=c-a[d-1].size),a.splice(d,1),f=!0)}d=0;I(a,function(a){var b=0;I(a.targets,function(){h[d].pos=a.pos+b;b+=h[d].size;d++})});h.push.apply(h,e);y(h,b)};c.prototype.drawDataLabels=function(){var a=this,c=a.options, +b=c.dataLabels,d=a.points,l,n,e=a.hasRendered||0,r,p,A=u(b.defer,!0),k=a.chart.renderer;if(b.enabled||a._hasPointLabels)a.dlProcessOptions&&a.dlProcessOptions(b),p=a.plotGroup("dataLabelsGroup","data-labels",A&&!e?"hidden":"visible",b.zIndex||6),A&&(p.attr({opacity:+e}),e||D(a,"afterAnimate",function(){a.visible&&p.show(!0);p[c.animation?"animate":"attr"]({opacity:1},{duration:200})})),n=b,I(d,function(e){var d,m=e.dataLabel,q,g,t=e.connector,F=!0,x,A={};l=e.dlOptions||e.options&&e.options.dataLabels; +d=u(l&&l.enabled,n.enabled)&&null!==e.y;if(m&&!d)e.dataLabel=m.destroy();else if(d){b=v(n,l);x=b.style;d=b.rotation;q=e.getLabelConfig();r=b.format?f(b.format,q):b.formatter.call(q,b);x.color=u(b.color,x.color,a.color,"#000000");if(m)G(r)?(m.attr({text:r}),F=!1):(e.dataLabel=m=m.destroy(),t&&(e.connector=t.destroy()));else if(G(r)){m={fill:b.backgroundColor,stroke:b.borderColor,"stroke-width":b.borderWidth,r:b.borderRadius||0,rotation:d,padding:b.padding,zIndex:1};"contrast"===x.color&&(A.color=b.inside|| +0>b.distance||c.stacking?k.getContrast(e.color||a.color):"#000000");c.cursor&&(A.cursor=c.cursor);for(g in m)void 0===m[g]&&delete m[g];m=e.dataLabel=k[d?"text":"label"](r,0,-9999,b.shape,null,null,b.useHTML,null,"data-label").attr(m);m.addClass("highcharts-data-label-color-"+e.colorIndex+" "+(b.className||"")+(b.useHTML?"highcharts-tracker":""));m.css(h(x,A));m.add(p);m.shadow(b.shadow)}m&&a.alignDataLabel(e,m,b,null,F)}})};c.prototype.alignDataLabel=function(a,c,b,d,f){var m=this.chart,e=m.inverted, +l=u(a.plotX,-9999),n=u(a.plotY,-9999),p=c.getBBox(),k,q=b.rotation,t=b.align,v=this.visible&&(a.series.forceDL||m.isInsidePlot(l,Math.round(n),e)||d&&m.isInsidePlot(l,e?d.x+1:d.y+d.height-1,e)),z="justify"===u(b.overflow,"justify");v&&(k=b.style.fontSize,k=m.renderer.fontMetrics(k,c).b,d=h({x:e?m.plotWidth-n:l,y:Math.round(e?m.plotHeight-l:n),width:0,height:0},d),h(b,{width:p.width,height:p.height}),q?(z=!1,e=m.renderer.rotCorr(k,q),e={x:d.x+b.x+d.width/2+e.x,y:d.y+b.y+{top:0,middle:.5,bottom:1}[b.verticalAlign]* +d.height},c[f?"attr":"animate"](e).attr({align:t}),l=(q+720)%360,l=180l,"left"===t?e.y-=l?p.height:0:"center"===t?(e.x-=p.width/2,e.y-=p.height/2):"right"===t&&(e.x-=p.width,e.y-=l?0:p.height)):(c.align(b,null,d),e=c.alignAttr),z?this.justifyDataLabel(c,b,e,p,d,f):u(b.crop,!0)&&(v=m.isInsidePlot(e.x,e.y)&&m.isInsidePlot(e.x+p.width,e.y+p.height)),b.shape&&!q&&c.attr({anchorX:a.plotX,anchorY:a.plotY}));v||(c.attr({y:-9999}),c.placed=!1)};c.prototype.justifyDataLabel=function(a,c,b,d,f,h){var e= +this.chart,m=c.align,l=c.verticalAlign,n,k,p=a.box?0:a.padding||0;n=b.x+p;0>n&&("right"===m?c.align="left":c.x=-n,k=!0);n=b.x+d.width-p;n>e.plotWidth&&("left"===m?c.align="right":c.x=e.plotWidth-n,k=!0);n=b.y+p;0>n&&("bottom"===l?c.verticalAlign="top":c.y=-n,k=!0);n=b.y+d.height-p;n>e.plotHeight&&("top"===l?c.verticalAlign="bottom":c.y=e.plotHeight-n,k=!0);k&&(a.placed=!h,a.align(c,null,f))};n.pie&&(n.pie.prototype.drawDataLabels=function(){var d=this,f=d.data,b,h=d.chart,l=d.options.dataLabels,n= +u(l.connectorPadding,10),e=u(l.connectorWidth,1),r=h.plotWidth,v=h.plotHeight,A,k=l.distance,w=d.center,y=w[2]/2,D=w[1],G=0m-2?u:H,e),g._attr={visibility:P,align:L[6]},g._pos={x:E+l.x+({left:n,right:-n}[L[6]]||0),y:H+l.y-10},L.x=E,L.y=H,null===d.options.size&&(B=g.width,E-Br-n&& +(O[1]=Math.max(Math.round(E+B-r+n),O[1])),0>H-M/2?O[0]=Math.max(Math.round(-H+M/2),O[0]):H+M/2>v&&(O[2]=Math.max(Math.round(H+M/2-v),O[2])))}),0===C(O)||this.verifyDataLabelOverflow(O))&&(this.placeDataLabels(),G&&e&&I(this.points,function(a){var b;A=a.connector;if((g=a.dataLabel)&&g._pos&&a.visible){P=g._attr.visibility;if(b=!A)a.connector=A=h.renderer.path().addClass("highcharts-data-label-connector highcharts-color-"+a.colorIndex).add(d.dataLabelsGroup),A.attr({"stroke-width":e,stroke:l.connectorColor|| +a.color||"#666666"});A[b?"attr":"animate"]({d:d.connectorPath(a.labelPos)});A.attr("visibility",P)}else A&&(a.connector=A.destroy())}))},n.pie.prototype.connectorPath=function(a){var c=a.x,b=a.y;return u(this.options.dataLabels.softConnector,!0)?["M",c+("left"===a[6]?5:-5),b,"C",c,b,2*a[2]-a[4],2*a[3]-a[5],a[2],a[3],"L",a[4],a[5]]:["M",c+("left"===a[6]?5:-5),b,"L",a[2],a[3],"L",a[4],a[5]]},n.pie.prototype.placeDataLabels=function(){I(this.points,function(a){var c=a.dataLabel;c&&a.visible&&((a=c._pos)? +(c.attr(c._attr),c[c.moved?"animate":"attr"](a),c.moved=!0):c&&c.attr({y:-9999}))})},n.pie.prototype.alignDataLabel=l,n.pie.prototype.verifyDataLabelOverflow=function(a){var c=this.center,b=this.options,f=b.center,h=b.minSize||80,l,e;null!==f[0]?l=Math.max(c[2]-Math.max(a[1],a[3]),h):(l=Math.max(c[2]-a[1]-a[3],h),c[0]+=(a[3]-a[1])/2);null!==f[1]?l=Math.max(Math.min(l,c[2]-Math.max(a[0],a[2])),h):(l=Math.max(Math.min(l,c[2]-a[0]-a[2]),h),c[1]+=(a[0]-a[2])/2);lu(this.translatedThreshold,e.yAxis.len)),p=u(b.inside,!!this.options.stacking);m&&(f=v(m),0>f.y&&(f.height+=f.y,f.y=0),m=f.y+f.height-e.yAxis.len,0a+d||e+lc+f||h+mthis.pointCount))}, +pan:function(a,b){var c=this,e=c.hoverPoints,d;e&&p(e,function(a){a.setState()});p("xy"===b?[1,0]:[1],function(b){b=c[b?"xAxis":"yAxis"][0];var e=b.horiz,f=a[e?"chartX":"chartY"],e=e?"mouseDownX":"mouseDownY",h=c[e],k=(b.pointRange||0)/2,g=b.getExtremes(),l=b.toValue(h-f,!0)+k,k=b.toValue(h+b.len-f,!0)-k,m=kk&&0>g&&(b.setExtremes(h,l,!1,!1,{trigger:"pan"}),d=!0);c[e]=f});d&&c.redraw(!1);I(c.container, +{cursor:"move"})}});v(m.prototype,{select:function(a,b){var c=this,e=c.series,f=e.chart;a=t(a,!c.selected);c.firePointEvent(a?"select":"unselect",{accumulate:b},function(){c.selected=c.options.selected=a;e.options.data[d(c,e.data)]=c.options;c.setState(a&&"select");b||p(f.getSelectedPoints(),function(a){a.selected&&a!==c&&(a.selected=a.options.selected=!1,e.options.data[d(a,e.data)]=a.options,a.setState(""),a.firePointEvent("unselect"))})})},onMouseOver:function(a,b){var c=this.series,e=c.chart,d= +e.tooltip,f=e.hoverPoint;if(this.series){if(!b){if(f&&f!==this)f.onMouseOut();if(e.hoverSeries!==c)c.onMouseOver();e.hoverPoint=this}!d||d.shared&&!c.noSharedTooltip?d||this.setState("hover"):(this.setState("hover"),d.refresh(this,a));this.firePointEvent("mouseOver")}},onMouseOut:function(){var a=this.series.chart,b=a.hoverPoints;this.firePointEvent("mouseOut");b&&-1!==d(this,b)||(this.setState(),a.hoverPoint=null)},importEvents:function(){if(!this.hasImportedEvents){var a=y(this.series.options.point, +this.options).events,b;this.events=a;for(b in a)D(this,b,a[b]);this.hasImportedEvents=!0}},setState:function(a,b){var c=Math.floor(this.plotX),d=this.plotY,e=this.series,h=e.options.states[a]||{},l=f[e.type].marker&&e.options.marker,m=l&&!1===l.enabled,n=l&&l.states&&l.states[a]||{},p=!1===n.enabled,g=e.stateMarkerGraphic,q=this.marker||{},u=e.chart,y=e.halo,z,F=l&&e.markerAttribs;a=a||"";if(!(a===this.state&&!b||this.selected&&"select"!==a||!1===h.enabled||a&&(p||m&&!1===n.enabled)||a&&q.states&& +q.states[a]&&!1===q.states[a].enabled)){F&&(z=e.markerAttribs(this,a));if(this.graphic)this.state&&this.graphic.removeClass("highcharts-point-"+this.state),a&&this.graphic.addClass("highcharts-point-"+a),this.graphic.attr(e.pointAttribs(this,a)),z&&this.graphic.animate(z,t(u.options.chart.animation,n.animation,l.animation)),g&&g.hide();else{if(a&&n){l=q.symbol||e.symbol;g&&g.currentSymbol!==l&&(g=g.destroy());if(g)g[b?"animate":"attr"]({x:z.x,y:z.y});else l&&(e.stateMarkerGraphic=g=u.renderer.symbol(l, +z.x,z.y,z.width,z.height).add(e.markerGroup),g.currentSymbol=l);g&&g.attr(e.pointAttribs(this,a))}g&&(g[a&&u.isInsidePlot(c,d,u.inverted)?"show":"hide"](),g.element.point=this)}(c=h.halo)&&c.size?(y||(e.halo=y=u.renderer.path().add(F?e.markerGroup:e.group)),y[b?"animate":"attr"]({d:this.haloPath(c.size)}),y.attr({"class":"highcharts-halo highcharts-color-"+t(this.colorIndex,e.colorIndex)}),y.point=this,y.attr(v({fill:this.color||e.color,"fill-opacity":c.opacity,zIndex:-1},c.attributes))):y&&y.point&& +y.point.haloPath&&y.animate({d:y.point.haloPath(0)});this.state=a}},haloPath:function(a){return this.series.chart.renderer.symbols.circle(Math.floor(this.plotX)-a,this.plotY-a,2*a,2*a)}});v(b.prototype,{onMouseOver:function(){var a=this.chart,b=a.hoverSeries;if(b&&b!==this)b.onMouseOut();this.options.events.mouseOver&&l(this,"mouseOver");this.setState("hover");a.hoverSeries=this},onMouseOut:function(){var a=this.options,b=this.chart,c=b.tooltip,d=b.hoverPoint;b.hoverSeries=null;if(d)d.onMouseOut(); +this&&a.events.mouseOut&&l(this,"mouseOut");!c||a.stickyTracking||c.shared&&!this.noSharedTooltip||c.hide();this.setState()},setState:function(a){var b=this,c=b.options,d=b.graph,f=c.states,h=c.lineWidth,c=0;a=a||"";if(b.state!==a&&(p([b.group,b.markerGroup],function(c){c&&(b.state&&c.removeClass("highcharts-series-"+b.state),a&&c.addClass("highcharts-series-"+a))}),b.state=a,!f[a]||!1!==f[a].enabled)&&(a&&(h=f[a].lineWidth||h+(f[a].lineWidthPlus||0)),d&&!d.dashstyle))for(f={"stroke-width":h},d.attr(f);b["zone-graph-"+ +c];)b["zone-graph-"+c].attr(f),c+=1},setVisible:function(a,b){var c=this,d=c.chart,e=c.legendItem,f,h=d.options.chart.ignoreHiddenSeries,m=c.visible;f=(c.visible=a=c.options.visible=c.userOptions.visible=void 0===a?!m:a)?"show":"hide";p(["group","dataLabelsGroup","markerGroup","tracker","tt"],function(a){if(c[a])c[a][f]()});if(d.hoverSeries===c||(d.hoverPoint&&d.hoverPoint.series)===c)c.onMouseOut();e&&d.legend.colorizeItem(c,a);c.isDirty=!0;c.options.stacking&&p(d.series,function(a){a.options.stacking&& +a.visible&&(a.isDirty=!0)});p(c.linkedSeries,function(b){b.setVisible(a,!1)});h&&(d.isDirtyBox=!0);!1!==b&&d.redraw();l(c,f)},show:function(){this.setVisible(!0)},hide:function(){this.setVisible(!1)},select:function(a){this.selected=a=void 0===a?!this.selected:a;this.checkbox&&(this.checkbox.checked=a);l(this,a?"select":"unselect")},drawTracker:a.drawTrackerGraph})})(L);(function(a){var D=a.Chart,C=a.each,G=a.inArray,I=a.isObject,h=a.pick,f=a.splat;D.prototype.setResponsive=function(a){var f=this.options.responsive; +f&&f.rules&&C(f.rules,function(f){this.matchResponsiveRule(f,a)},this)};D.prototype.matchResponsiveRule=function(f,v){var l=this.respRules,p=f.condition,d;d=p.callback||function(){return this.chartWidth<=h(p.maxWidth,Number.MAX_VALUE)&&this.chartHeight<=h(p.maxHeight,Number.MAX_VALUE)&&this.chartWidth>=h(p.minWidth,0)&&this.chartHeight>=h(p.minHeight,0)};void 0===f._id&&(f._id=a.uniqueKey());d=d.call(this);!l[f._id]&&d?f.chartOptions&&(l[f._id]=this.currentOptions(f.chartOptions),this.update(f.chartOptions, +v)):l[f._id]&&!d&&(this.update(l[f._id],v),delete l[f._id])};D.prototype.currentOptions=function(a){function h(a,d,c){var l,p;for(l in a)if(-15', - onClick: function () { - $("#room").val("") - $(".create-actions01").empty().text(">5") - } - }) - - var buttons2 = [ - { - text: '�消', - bg: 'gray' - } - ]; - var groups = [buttons1, buttons2]; - $.actions(groups); -}); +// +// // 选择�作-房型-室 +// $(document).on('click', '.create-actions01', function () { +// var buttons1 = [ +// { +// text: '请选择室', +// label: true +// } +// ]; +// for (var i = 1; i < 6; i++) { +// buttons1.push({ +// text: i + '', +// onClick: function () { +// $("#room").val(this.text) +// $(".create-actions01").empty().text(this.text).addClass("selected") +// } +// }) +// } +// buttons1.push({ +// text: '>5', +// onClick: function () { +// $("#room").val("") +// $(".create-actions01").empty().text(">5") +// } +// }) +// +// var buttons2 = [ +// { +// text: '�消', +// bg: 'gray' +// } +// ]; +// var groups = [buttons1, buttons2]; +// $.actions(groups); +// }); // 选择�作-房型-� $(document).on('click', '.create-actions02', function () { @@ -144,7 +144,7 @@ $(document).on('click', '.create-actions03', function () { label: true }, { - text: '公寓', + text: '普通�宅', bold: true, onClick: function () { $("a.create-actions03").empty().text(this.text).addClass("selected") diff --git a/projects/fangjia-open/src/main/webapp/static/js/trend-charts.js b/projects/fangjia-open/src/main/webapp/static/js/trend-charts.js index dbd6dc45b..fbbe9a135 100644 --- a/projects/fangjia-open/src/main/webapp/static/js/trend-charts.js +++ b/projects/fangjia-open/src/main/webapp/static/js/trend-charts.js @@ -2,7 +2,7 @@ var chart = new Highcharts.Chart({ credits:{ enabled:true, - text: '房价网', + text: '', href: Constants.cityUrl, position: { align: 'center', @@ -76,7 +76,7 @@ type: 'spline' }, title: { - text: '房价网', + text: '', floating: false, align: 'center', x : 0, @@ -128,7 +128,7 @@ }, credits:{ enabled:true, - text: '房价网', + text: '', href: Constants.cityUrl, position: { align: 'center', diff --git a/projects/fangjia-open/src/main/webapp/user/aiLoginPage.ftl b/projects/fangjia-open/src/main/webapp/user/aiLoginPage.ftl new file mode 100644 index 000000000..cec747b40 --- /dev/null +++ b/projects/fangjia-open/src/main/webapp/user/aiLoginPage.ftl @@ -0,0 +1,167 @@ +<#ftl attributes={"content_type":"text/html; charset=UTF-8"}> +<#compress> + + + + + + +用户登录 + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/projects/fangjia-open/src/main/webapp/weiXinEvaluation/bhreport.ftl b/projects/fangjia-open/src/main/webapp/weiXinEvaluation/bhreport.ftl index a64bb2f90..2a1515696 100644 --- a/projects/fangjia-open/src/main/webapp/weiXinEvaluation/bhreport.ftl +++ b/projects/fangjia-open/src/main/webapp/weiXinEvaluation/bhreport.ftl @@ -460,7 +460,7 @@ <#include '/layout/footer.ftl'/> - + diff --git a/projects/fangjia-open/src/main/webapp/weiXinEvaluation/form.ftl b/projects/fangjia-open/src/main/webapp/weiXinEvaluation/form.ftl index 1f48d1dc5..8a35807f4 100644 --- a/projects/fangjia-open/src/main/webapp/weiXinEvaluation/form.ftl +++ b/projects/fangjia-open/src/main/webapp/weiXinEvaluation/form.ftl @@ -14,16 +14,25 @@ - + +〈 +
    -
    +
    @@ -83,9 +92,9 @@
    -
    建筑类型:
    +
    房屋类型:
    -

    请选择建筑类型

    +

    请选择房屋类型

    @@ -100,7 +109,7 @@ placeholder="请输入所在楼层" min="1" max="200"> + placeholder="请输入楼层�述">
    @@ -211,13 +220,33 @@
    +<#--
  • --> +<#--
    --> +<#--
    --> +<#--
    --> +<#--
    车�情况:
    --> +<#-- --> +<#--

    请选择车�情况

    --> +<#--
    --> +<#--
    --> +<#--
    --> +<#--
  • -->
  • -
    -
    车�情况:
    - -

    请选择车�情况

    +
    车��积:
    +
    + +
    +
    +
    +
  • +
  • +
    +
    +
    车�价:
    +
    +
    @@ -407,6 +436,13 @@ } }) }) + + if (typeof WeixinJSBridge !== "undefined") { + WeixinJSBridge.on('menu:back', function () { + window.history.back(); // 返回上一页 + }); + } + diff --git a/projects/fangjia-open/src/main/webapp/weiXinEvaluation/recordList.ftl b/projects/fangjia-open/src/main/webapp/weiXinEvaluation/recordList.ftl index 93cc7a993..cf6070a5c 100644 --- a/projects/fangjia-open/src/main/webapp/weiXinEvaluation/recordList.ftl +++ b/projects/fangjia-open/src/main/webapp/weiXinEvaluation/recordList.ftl @@ -13,11 +13,22 @@ - + - + +〈 + -
    +
    diff --git a/projects/fangjia-open/src/main/webapp/weiXinEvaluation/report.ftl b/projects/fangjia-open/src/main/webapp/weiXinEvaluation/report.ftl index fd5351b5d..821f5f2a7 100644 --- a/projects/fangjia-open/src/main/webapp/weiXinEvaluation/report.ftl +++ b/projects/fangjia-open/src/main/webapp/weiXinEvaluation/report.ftl @@ -16,11 +16,20 @@ - + +〈 +
    @@ -180,7 +189,7 @@ <#if evaluation?? && (fjtEvaluation.buildType)! == 3> �宅 <#elseif fjtEvaluation.buildType! == 8> - 公寓 + 普通�宅 <#elseif fjtEvaluation.buildType! == 4> 独立别墅 <#elseif fjtEvaluation.buildType! == 5> @@ -209,21 +218,22 @@ -

    -

    -

    - <#if role?? && role==16> -

    - - - <#if fjtEvaluation.onlyOne! == 1> - 是 - <#elseif fjtEvaluation.onlyOne! == 2> - � - <#else> - - - - -

    - +

    <#if fjtEvaluation.carSitePrice??>${fjtEvaluation.carSitePrice!}万元<#else>-

    + <#--

    -

    --> +<#-- <#if role?? && role==16>--> +<#--

    --> +<#-- --> +<#-- --> +<#-- <#if fjtEvaluation.onlyOne! == 1>--> +<#-- 是--> +<#-- <#elseif fjtEvaluation.onlyOne! == 2>--> +<#-- �--> +<#-- <#else>--> +<#-- - --> +<#-- --> +<#-- --> +<#--

    --> +<#-- -->

    @@ -273,10 +283,7 @@

    <#if fjtEvaluation.gardenArea??>${fjtEvaluation.gardenArea!?string('0.##')}平米<#else>-

    <#if fjtEvaluation.outerArea??>${fjtEvaluation.outerArea!?string('0.##')}平米<#else>-

    -

    <#if fjtEvaluation.carSiteArea??>${fjtEvaluation.carSiteArea!?string('0.##')}平米<#else>-

    - <#if fjtEvaluation.city! == "上海"> -

    ${fjtEvaluation.loopLine!}

    - +

    <#if fjtEvaluation.carSiteArea??>${fjtEvaluation.carSiteArea!?string('0.##')}平米<#else>-

    @@ -326,20 +333,23 @@

    <#if fjtEvaluation.basementArea??&&(fjtEvaluation.basementArea!>0)>${fjtEvaluation.basementArea!?string('0.##')}平米<#else>-

    <#if fjtEvaluation.basementArea??&&(fjtEvaluation.atticArea!>0)>${fjtEvaluation.atticArea!?string('0.##')}平米<#else>-

    -

    - - - <#if fjtEvaluation.carport! == 1> - 已租 - <#elseif fjtEvaluation.carport! == 3> - 已购 - <#elseif fjtEvaluation.carport! == 2> - 暂无 - <#else> - - - - -

    + <#if fjtEvaluation.city! == "上海"> +

    ${fjtEvaluation.loopLine!}

    + + <#--

    --> +<#-- --> +<#-- --> +<#-- <#if fjtEvaluation.carport! == 1>--> +<#-- 已租--> +<#-- <#elseif fjtEvaluation.carport! == 3>--> +<#-- 已购--> +<#-- <#elseif fjtEvaluation.carport! == 2>--> +<#-- 暂无--> +<#-- <#else>--> +<#-- ---> +<#-- --> +<#-- --> +<#--

    -->
    全部信�
    @@ -381,7 +391,7 @@ <#include '/layout/footer.ftl'/> - + + diff --git a/projects/fangjia-script/pom.xml b/projects/fangjia-script/pom.xml index e639f76e3..2b61cb696 100644 --- a/projects/fangjia-script/pom.xml +++ b/projects/fangjia-script/pom.xml @@ -537,6 +537,12 @@ 1.70 + + org.locationtech.jts + jts-core + 1.18.2 + + diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/PoseidonOnce.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/PoseidonOnce.groovy index fa4c6891f..48b616432 100644 --- a/projects/fangjia-script/src/main/groovy/com/fangjia/script/PoseidonOnce.groovy +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/PoseidonOnce.groovy @@ -78,7 +78,7 @@ class PoseidonOnce { // DBCursor cur = coll.find() // println cur.count() String url = "http://www.fangjia.com"; - DBCollection coll = MongoUtils.getCollectionByName("fangjia", "test2", "192.168.0.188") + DBCollection coll = MongoUtils.getCollectionByName("fangjia", "FiveLevelTest", "192.168.0.188") // for(int i=426000;i<1000000;i++) { // String s = url + i + "_" + url.hashCode() // DBObject dbo = new BasicDBObject() diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/ccbevaluation/AddSzDealData.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/ccbevaluation/AddSzDealData.groovy index 4473e1e49..dfd784e71 100644 --- a/projects/fangjia-script/src/main/groovy/com/fangjia/script/ccbevaluation/AddSzDealData.groovy +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/ccbevaluation/AddSzDealData.groovy @@ -8,7 +8,7 @@ import com.mongodb.DBCollection /** * ÉîÛÚ¹«Öںųɽ»Êý¾Ý¼Èë */ -def datas = ExcelUtils.read("D:\\Êý¾Ý\\2024Äê10ÔÂÉîÛÚ¶þÊÖ·¿³É½».xlsx", 0, 1) +def datas = ExcelUtils.read("D:\\Êý¾Ý\\½¨ÐÐ\\·¿²ú¹ÀÖµ\\³É½»\\2024Äê11ÔÂÉîÛÚ¶þÊÖ·¿³É½».xlsx", 0, 1) def lineUrl = "mongodb://developer:G00IDCDEV12385@192.168.0.43:28017"; DBCollection DEAL_PRICE_COLL = MongoUtils.getCollectionByName2("fangjia", "deal_price", lineUrl) diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/ccbevaluation/BigdataDealBatch.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/ccbevaluation/BigdataDealBatch.groovy index c65f09175..f6baf3541 100644 --- a/projects/fangjia-script/src/main/groovy/com/fangjia/script/ccbevaluation/BigdataDealBatch.groovy +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/ccbevaluation/BigdataDealBatch.groovy @@ -71,8 +71,7 @@ class BigdataDealBatch extends BaseBatch{ for(def city : allCitys){ addDealPriceMatch(city); } - updateCrawlTradeDate()//Ð޸ĺóץȡµÄ³É½»£¬½«Ê±¼ä¸ÄΪ±¾Ô - +// updateCrawlTradeDate()//Ð޸ĺóץȡµÄ³É½»£¬½«Ê±¼ä¸ÄΪ±¾Ô def rows = [] def headers = []//["³ÇÊÐID","³É½»ID","³ÇÊÐÃû³Æ","ÐÐÕþÇøID","ÐÐÕþÇøÃû³Æ","½ÖµÀ","ÃÅÅÆºÅ","Ð¡ÇøID","Ð¡ÇøÃû³Æ","Â¥¶°ID","Â¥¶°±àºÅ","Â¥¶°Ãû³Æ","µ¥ÔªID","µ¥Ôª±àºÅ","µ¥ÔªÃû³Æ","»§ID","ÏêϸµØÖ·","½¨ÖþÄê´ú","ȨÊô","ȨÊôÄêÏÞ","ÆÚÊý","ËùÔÚÂ¥²ã","²ãÀàÐÍ","×ÜÂ¥²ãÊý","½¨ÖþÀàÐÍ","½¨Öþ½á¹¹","½¨ÖþÃæ»ý","Ì×ÄÚÃæ»ý","»§ÐÍ","ÊÒ","Ìü","³ø","ÎÀ","·¿ÎÝÓÃ;","ÊÒÄڽṹ","³¯Ïò","×°ÐÞÇé¿ö","ÆÀ¹À±àºÅ","³É½»µ¥¼Û","³É½»×ܼÛ","É걨×ܼÛ","ÆÀ¹À×ܼÛ","ÍøÇ©ºÏͬ±àºÅ","½»Ò×ÈÕÆÚ","½»Ò×ÀàÐÍ","³öÊÛ¸¶¿î·½Ê½","³É½»ÖÜÆÚ","ÊÇ·ñÓеçÌÝ","ÔùËÍÃæ»ý£¨µØÃ滨԰£©","ÔùËÍÃæ»ý£¨Â¶Ì¨£©","ÔùËÍÃæ»ý£¨Ñǫ̂£©","ÔùËÍÃæ»ý£¨Æ®´°£©","ÔùËÍÃæ»ý£¨¸óÂ¥£©","ÔùËÍÃæ»ý£¨³µ¿â£©","ÔùËÍÃæ»ý£¨µØÏÂÊÒ£©","ÔùËÍÃæ»ý£¨ÆäËû£©","·¿Ô´Êý¾ÝÀ´Ô´","Öн鹫˾ID","Öн鹫˾Ãû³Æ","±¸×¢","´´½¨Ê±¼ä","¸üÐÂʱ¼ä","À´Ô´¹«Ë¾","³É½»½ð¶î","Êý¾Ýʱ¼ä"] diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/ccbevaluation/ThirdPartyPriceBatch.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/ccbevaluation/ThirdPartyPriceBatch.groovy index 98612d573..ffd743d5c 100644 --- a/projects/fangjia-script/src/main/groovy/com/fangjia/script/ccbevaluation/ThirdPartyPriceBatch.groovy +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/ccbevaluation/ThirdPartyPriceBatch.groovy @@ -30,8 +30,11 @@ class ThirdPartyPriceBatch extends BaseBatch { static final DBCollection AVERAGE_STATISTICS = MongoUtils.getCollectionByName("fangjia", "average_statistics", "192.168.0.43") DBCollection DIST_SELL_STAT = MongoUtils.getCollectionByName("fangjia_stat", "district_stat", "mongo.db.fangjia.com") - def sourceMap = ["Öî¸ðÕÒ·¿":"01", "°²¾Ó¿Í":"02","·¿ÌìÏÂ":"03","Á´¼Ò":"04","³ÇÊмҾÓ":"05","ÂóÌï":"06","±´¿Ç":"07","ÌÔ·¿365":"08","ÖÐÔ­":"09","Íò©Ê¿":"10","Q·¿":"11","·¿Ì½":"12", - "·¿¶à¶à":"13","ÎÒ°®ÎÒ¼Ò":"14","ìûÌ©Êý¾Ý":"15","¼ªÎÝÍø":"16","ÀÖ¾Ó":"17","21ÊÀ¼Í":"18","·¿²ú³¬ÊÐ":"19","58ͬ³Ç":"20"] + def sourceMap = ["Öî¸ðÕÒ·¿":"01", "°²¾Ó¿Í":"02","·¿ÌìÏÂ":"03","Á´¼Ò":"04","³ÇÊмҾÓ":"05","ÂóÌï":"06","±´¿Ç":"07", + "ÌÔ·¿365":"08","ÖÐÔ­":"09","Íò©Ê¿":"10","Q·¿":"11","·¿Ì½":"12","·¿¶à¶à":"13","ÎÒ°®ÎÒ¼Ò":"14", + "ìûÌ©Êý¾Ý":"15","¼ªÎÝÍø":"16","ÀÖ¾Ó":"17","21ÊÀ¼Í":"18","·¿²ú³¬ÊÐ":"19","58ͬ³Ç":"20", + "ÀÖÓмÒ":"21","ÐÒ¸£Àï":"22","Öйú·¿¼ÛÐÐÇé":"23","³£ÖÝס·¿":"24" + ] def sqlInstance = Sql.newInstance("jdbc:oracle:thin:@192.168.0.236:1521:orcl", "GOOJIA", "GOOJIA", "oracle.jdbc.driver.OracleDriver") @@ -263,6 +266,30 @@ class ThirdPartyPriceBatch extends BaseBatch { if(third.get("csjj_esf_price")){ price_map.csjj_avg_price = third.get("csjj_esf_price") } + + if(third.get("leyoujia_esf_price")){ + price_map.leyoujia_avg_price = third.get("leyoujia_esf_price") + } + + if(third.get("c21_esf_price")){ + price_map.c21_avg_price = third.get("c21_esf_price") + } + + if(third.get("jiwu_esf_price")){ + price_map.jiwu_avg_price = third.get("jiwu_esf_price") + } + + if(third.get("xingfuli_esf_price")){ + price_map.xingfuli_avg_price = third.get("xingfuli_esf_price") + } + + if(third.get("zwfc_esf_price")){ + price_map.zwfc_avg_price = third.get("zwfc_esf_price") + } + + if(third.get("creprice_esf_price")){ + price_map.creprice_avg_price = third.get("creprice_esf_price") + } dataMap.updatetime = DateUtils.formatDateByPattern(new Date(), "yyyy-MM-dd HH:mm:ss") allRows << dataMap } @@ -313,6 +340,18 @@ class ThirdPartyPriceBatch extends BaseBatch { web = "·¿²ú³¬ÊÐ" }else if(k=="csjj_avg_price"){ web = "³ÇÊоӼÒ" + }else if(k=="leyoujia_avg_price"){ + web = "ÀÖÓмÒ" + }else if(k=="c21_avg_price"){ + web = "C21" + }else if(k=="jiwu_avg_price"){ + web = "¼ªÎÝÍø" + }else if(k=="xingfuli_avg_price"){ + web = "ÐÒ¸£Àï" + }else if(k=="creprice_avg_price"){ + web = "Öйú·¿¼ÛÐÐÇé" + }else if(k=="zwfc_avg_price"){ + web = "³£ÖÝס·¿" } ret << sourceMap.get(web) @@ -603,6 +642,30 @@ class ThirdPartyPriceBatch extends BaseBatch { if(!dataMap.get("csjj_esf_price") && db.get("csjj_esf_price") && db.get("csjj_esf_price")>3000){ dataMap.put("csjj_esf_price", db.get("csjj_esf_price")) } + + if(!dataMap.get("leyoujia_esf_price") && db.get("leyoujia_esf_price") && db.get("leyoujia_esf_price")>3000){ + dataMap.put("leyoujia_esf_price", db.get("leyoujia_esf_price")) + } + + if(!dataMap.get("c21_esf_price") && db.get("c21_esf_price") && db.get("c21_esf_price")>3000){ + dataMap.put("c21_esf_price", db.get("c21_esf_price")) + } + + if(!dataMap.get("jiwu_esf_price") && db.get("jiwu_esf_price") && db.get("jiwu_esf_price")>3000){ + dataMap.put("jiwu_esf_price", db.get("jiwu_esf_price")) + } + + if(!dataMap.get("xingfuli_esf_price") && db.get("xingfuli_esf_price") && db.get("xingfuli_esf_price")>3000){ + dataMap.put("xingfuli_esf_price", db.get("xingfuli_esf_price")) + } + + if(!dataMap.get("creprice_esf_price") && db.get("creprice_esf_price") && db.get("creprice_esf_price")>3000){ + dataMap.put("creprice_esf_price", db.get("creprice_esf_price")) + } + + if(!dataMap.get("zwfc_esf_price") && db.get("zwfc_esf_price") && db.get("zwfc_esf_price")>3000){ + dataMap.put("zwfc_esf_price", db.get("zwfc_esf_price")) + } // if(db.zhugezhaofang_esf_price || db.anjuke_esf_price ||db.soufang_esf_price || db.lianjia_esf_price || db.cityhouse_esf_price || db.maitian_esf_price || db.beike_esf_price || db.get("365house_esf_price") || db.zhongyuan_esf_price || db.tuboshi_esf_price || db.qfang_esf_price || db.fangtan_esf_price || db.fangduoduo_esf_price || db.get("5i5j_esf_price")){ // map.put(key, db) // } diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/commData/CommonDatautils.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/commData/CommonDatautils.groovy index 9db36e3d8..82cffedbd 100644 --- a/projects/fangjia-script/src/main/groovy/com/fangjia/script/commData/CommonDatautils.groovy +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/commData/CommonDatautils.groovy @@ -103,6 +103,8 @@ class CommonDatautils { public static final DBCollection STATS_INDEX_COLL = MongoUtils.getCollectionByName("fangjia_stat", "stats_index", "mongo.db.fangjia.com") + public static final DBCollection bk_business_coll = MongoUtils.getCollectionByName("fangjia_base", "bk_business", "mongo.db.fangjia.com") + public static DSCollection getHouseDataStoreConnection(){ if(house_dataStoreConnection != null) { return house_dataStoreConnection @@ -597,9 +599,9 @@ class CommonDatautils { keys.put("region", 1); keys.put("name", 1); keys.put("_id", 1); - DSCursor cursor = getDataStoreConnection().find(q, keys).batchSize(2000); + DSCursor cursor = DbUtils.seaweed.find(q, keys).batchSize(2000); Iterator iters = cursor.iterator() - def result = []; + def result = new HashSet(); try{ while(iters.hasNext()) { DBObject obj = iters.next() @@ -4209,19 +4211,21 @@ class CommonDatautils { static def findAllNewPoiDatas(city){ - String sql = "select pname,cityname,adname,name,address,location,type,id from poi_amap_2024 where cityname='${city}'" + String sql = "select cityname,adname,name,address,location,type,id,parent from amap_poi_2024 where cityname='${city}'" def rets = [] def index= 0 ElasticUtils.executeSqlQuery(sql, { map-> // if(map.address && map.address.contains("Îå½Ç³¡")){ index++ - rets << ["map_id":map.id,"province":map.pname,"city":map.cityname, "district":map.adname, "name":map.name, "address":map.address, "cat":map.type,"lng":map.location.x, "lat":map.location.y] + rets << ["map_id":map.id,"province":map.pname,"city":map.cityname, "district":map.adname, "name":map.name, "address":map.address, "cat":map.type,"lng":map.location.x, "lat":map.location.y, "parent_id":map.parent] // } }) return rets; } + + static def findOneThirdNetWorkOffice(city, region, name){ String sql = "select location from office where city='${city}' and region='${region}' and name='${name}'" def map = [:] @@ -4965,6 +4969,20 @@ class CommonDatautils { return regionMap } + static def queryRangeByCat(cat){ + def q = new BasicDBObject() + q.put("type",cat) + q.put("shape",new BasicDBObject('$exists', true)) + def keys = new BasicDBObject() + keys.put("city_short",1) + keys.put("district_short",1) + keys.put("city",1) + keys.put("district",1) + keys.put("mzb_district_name", 1) + keys.put("shape", 1) + return ADMINISTRATIVE_MAPPING_COLL.find(q,keys).toList() + } + static def queryAllRegionNameByCity(){ @@ -5135,17 +5153,22 @@ class CommonDatautils { def dbcursor = ADMINISTRATIVE_MAPPING_COLL.find(q, keys).batchSize(5000).addOption(Bytes.QUERYOPTION_NOTIMEOUT) def townMap = [:] for(def d : dbcursor){ + def distName = null if(d.mzb_district_name){ - def list = townMap.get(d.mzb_district_name) + distName = d.mzb_district_name + }else{ + distName = d.district + } + if(distName){ + def list = townMap.get(distName) if(!list){ list = [] } list << d - townMap.put(d.mzb_district_name, list) + townMap.put(distName, list) } } - - println "[${city}] ÏçÕò½ÖµÀ ¼ÓÔØÍê³É "+new Date().format("yyyy-MM-dd HH:mm:ss") +// println "[${city}] ÏçÕò½ÖµÀ ¼ÓÔØÍê³É "+new Date().format("yyyy-MM-dd HH:mm:ss") return townMap } @@ -5515,4 +5538,10 @@ class CommonDatautils { return 0 } + static def findBusinessByCity(city){ + def q = new BasicDBObject() + q.put("short_city", city) + return bk_business_coll.find(q).toList() + } + } diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/dataAna/CityInfoAnaBatch.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/dataAna/CityInfoAnaBatch.groovy index d008b0f48..8511662a1 100644 --- a/projects/fangjia-script/src/main/groovy/com/fangjia/script/dataAna/CityInfoAnaBatch.groovy +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/dataAna/CityInfoAnaBatch.groovy @@ -343,21 +343,21 @@ class CityInfoAnaBatch extends BaseBatch { def totalDbhouseloudongCount = HOUSE_LOUDONG_CONN.count(findObj) datas << ['', totalDistrictCount, totalLoudongCount, df.format(totalLoudongCount * 1.0/ totalDistrictCount), totalFanghaoCount, df.format(totalFanghaoCount * 1.0/ totalDistrictCount), totalDbLoudongCount, totalDbhouseloudongCount] - ExcelUtils.write(fileName, datas, resultTitle) - String id = ObjectId.get().toString() - BasicDBObject file = new BasicDBObject() - file.put("t", "upload") - file.put("content_type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") - file.put("c_date", new Date()) - file.put("_id", idGenerator(id, "o")) - file.put("data", new File(fileName).getBytes()) - fsDB.save(file) - def href = DataUtil.encodePicUrl(id, "o", "upload") - href = "µã»÷ÏÂÔØ¸½¼þ" - receivers.each {receiver-> - jms.sendMail(receiver, resultTitle, href) - } - new File(fileName).deleteOnExit() +// ExcelUtils.write(fileName, datas, resultTitle) +// String id = ObjectId.get().toString() +// BasicDBObject file = new BasicDBObject() +// file.put("t", "upload") +// file.put("content_type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") +// file.put("c_date", new Date()) +// file.put("_id", idGenerator(id, "o")) +// file.put("data", new File(fileName).getBytes()) +// fsDB.save(file) +// def href = DataUtil.encodePicUrl(id, "o", "upload") +// href = "µã»÷ÏÂÔØ¸½¼þ" +// receivers.each {receiver-> +// jms.sendMail(receiver, resultTitle, href) +// } +// new File(fileName).deleteOnExit() } private String idGenerator(String url, String size) { diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/dealPrice/SynchDealPriceToEs.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/dealPrice/SynchDealPriceToEs.groovy new file mode 100644 index 000000000..dba4650b9 --- /dev/null +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/dealPrice/SynchDealPriceToEs.groovy @@ -0,0 +1,140 @@ +package com.fangjia.script.dealPrice + +import com.fangjia.core.util.MongoUtils +import com.fangjia.script.BaseBatch +import com.fangjia.script.BatchOwner +import com.fangjia.script.Watcher +import com.fangjia.script.gj.xiamen.ElasticUtils89 +import com.fangjia.script.util.DateUtils +import com.fangjia.script.util.ElasticUtils +import com.mongodb.AggregationOutput +import com.mongodb.BasicDBObject +import com.mongodb.DBCollection +import com.mongodb.DBObject +import org.elasticsearch.action.bulk.BulkRequest +import org.elasticsearch.action.bulk.BulkResponse +import org.elasticsearch.action.index.IndexRequest +import org.elasticsearch.action.support.WriteRequest +import org.elasticsearch.client.RequestOptions +import org.elasticsearch.common.xcontent.XContentType + +/** + * ³É½»Í¬²½206£¬°´ÈÕͬ²½ + */ +@BatchOwner(Watcher.GaoJuan) +class SynchDealPriceToEs extends BaseBatch{ + static DBCollection dealPriceConn = MongoUtils.getCollectionByName("fangjia", "deal_price", "192.168.0.43",28017) + + static main(args) { + runBatch(new SynchDealPriceToEs(), args) + } + + + @Override + void process(Object args) { + run(); + } + + def run(){ + def startDate = DateUtils.formatDateByPattern(new Date()-1, "yyyy-MM-dd") + def q = new BasicDBObject() + q.put("m_date", new BasicDBObject('$gte', DateUtils.parseFromTightYYYYMMDD(startDate))) + def dbcursor = dealPriceConn.find(q) + println DateUtils.formatDateByPattern(new Date(),"yyyy-MM-dd")+" ¸üÐÂÁ¿£º"+ dbcursor.count() + def ret = [] + for(def o : dbcursor){ + ret << o + } + save(ret) + +// def batchsize = 2000 +// def citys = getCityCount() +// citys.each{city,count-> +// if(city instanceof String){ +// for(def year = 1999;year<=2025;year++){ +// def q = new BasicDBObject("city", city) +// q.put("trade_date", new BasicDBObject('$gte', DateUtils.parseFromTightByPattern(year+"-01-01", "yyyy-MM-dd")).append('$lte', DateUtils.parseFromTightByPattern(year+1+"-01-01", "yyyy-MM-dd"))) +// def dbcursor = dealPriceConn.find(q).batchSize(batchsize) +// println city +" "+ dbcursor.count() +// def ret = [] +// for(def o : dbcursor){ +// ret << o +// } +// save(ret) +// } +// } +// } + } + + + def getCityCount(){ + + BasicDBObject match = null; + // ¶¨Òå¾ÛºÏ¹ÜµÀ£¬°´ city ×ֶηÖ×飬²¢¼ÆËãÿ¸ö³ÇÊеÄÊýÁ¿ + DBObject groupFields = new BasicDBObject(); + +// match = new BasicDBObject('$match', new BasicDBObject("level", "³ÇÊÐ")); + groupFields.put("_id", new BasicDBObject("city",'$city')) + + groupFields.put("count", new BasicDBObject('$sum', 1)); + DBObject group = new BasicDBObject('$group', groupFields); + + // Ö´Ðоۺϲéѯ + AggregationOutput output = dealPriceConn.aggregate(Arrays.asList(group)); + def map = [:] + // ±éÀú½á¹û + for (DBObject result : output.results()) { + def obj = (DBObject ) result.get("_id"); + if(obj.get("city")) { + int count = (Integer) result.get("count"); + map.put(obj.get("city"), count) + } + } + return map; + } + + + + def save(rows){ + BulkRequest request = new BulkRequest(); + int batchSize = 500; + int processedCount = 0; + def client = ElasticUtils.getClient("192.168.0.206") + + for(def map : rows){ +// def map = rows.get(key) + def data_id = map._id.toString() + map.remove("_id") + request.add(new IndexRequest("trades", "_doc", data_id).source(map, XContentType.JSON)); + + // ÅúÁ¿Ìá½»Êý¾Ý + if (request.numberOfActions() >= batchSize) { + request.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); + BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT); + if (bulkResponse.hasFailures()) { + // ´¦Àí´íÎó + print "Bulk request has failures: " + bulkResponse.buildFailureMessage() + } else { + processedCount += request.numberOfActions(); + println "Processed " + processedCount + " documents "+new Date().format("yyyy-MM-dd HH:mm:ss") + } + + request = new BulkRequest(); + } + } + + if (request.numberOfActions() > 0) { + request.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); + BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT); + if (bulkResponse.hasFailures()) { + // ´¦Àí´íÎó + println "Bulk request has failures: " + bulkResponse.buildFailureMessage() + } else { + processedCount += request.numberOfActions(); + println "Processed " + processedCount + " documents" + } + } + + } + +} diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/FiledStrand.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/FiledStrand.groovy index a3c119bec..514dd9631 100644 --- a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/FiledStrand.groovy +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/FiledStrand.groovy @@ -909,14 +909,18 @@ class FiledStrand { } static def getNumber(def input) { - Pattern pattern = Pattern.compile("\\d+(\\.\\d+)?"); - Matcher matcher = pattern.matcher(input); - List list = new ArrayList(); - while (matcher.find()) { - list.add(matcher.group()); - } - if(list.size()>0){ - return list.get(0); + try{ + Pattern pattern = Pattern.compile("\\d+(\\.\\d+)?"); + Matcher matcher = pattern.matcher(input); + List list = new ArrayList(); + while (matcher.find()) { + list.add(matcher.group()); + } + if(list.size()>0){ + return list.get(0); + } + }catch(Exception e){ + println input+" error" } return null; } diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/ProxyHttpUtils.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/ProxyHttpUtils.groovy new file mode 100644 index 000000000..72495191d --- /dev/null +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/ProxyHttpUtils.groovy @@ -0,0 +1,62 @@ +package com.fangjia.script.gj + +import groovy.json.JsonOutput + +class ProxyHttpUtils { + + static String proxyHost = 'tunnel2.qg.net'; + static Integer proxyPort = 14186; + static String proxyUsername = '113BBC06'; + static String proxyPassword = '3B2FBD05B0AF'; + + static String getProxyResult(targetUrl, data){ + // ½« JSON ¶ÔÏóת»»Îª×Ö·û´® + String jsonData = new JsonOutput().toJson(data); + // ´´½¨´úÀí¶ÔÏó + Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); + + // ´´½¨ URL ¶ÔÏó + URL url = new URL(targetUrl); + + // ´´½¨Á¬½Ó¶ÔÏó + URLConnection connection = url.openConnection(proxy); + + // ÉèÖôúÀíÈÏÖ¤ + java.net.Authenticator.setDefault(new java.net.Authenticator() { + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(proxyUsername, proxyPassword.toCharArray()) + } + }) + + // ÉèÖÃÇëÇó·½·¨Îª POST + connection.setRequestMethod("POST"); + + // ÔÊÐíÊä³öÁ÷ + connection.setDoOutput(true); + + // ÉèÖÃÇëÇóÍ· + connection.setRequestProperty("Content-Type", "application/json"); + + // ·¢ËÍÇëÇó²ÎÊý + OutputStream outputStream = connection.getOutputStream(); + outputStream.write(jsonData.getBytes("UTF-8")); + outputStream.flush(); + outputStream.close(); + + // ¶ÁÈ¡ÏìÓ¦ + int responseCode = connection.getResponseCode() + if (responseCode == HttpURLConnection.HTTP_OK) { + BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); + StringBuilder response = new StringBuilder(); + String line; + while ((line = reader.readLine()) != null) { + response.append(line); + } + reader.close(); + return response.toString(); + } else { + println "HTTP request failed with response code ${responseCode}"; + } + return null; + } +} diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/coresite/AddUrlToBaiduSpider.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/coresite/AddUrlToBaiduSpider.groovy new file mode 100644 index 000000000..2b03fd2ae --- /dev/null +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/coresite/AddUrlToBaiduSpider.groovy @@ -0,0 +1,48 @@ +package com.fangjia.script.gj.coresite + +import java.net.HttpURLConnection +import java.net.URL +import java.io.OutputStream + +// Ä¿±ê·þÎñÆ÷µÄURL +def targetUrlString = "http://data.zz.baidu.com/urls?site=sh.fangjia.com&token=UaKTemkcQ6I4YvSA" + +// ÐèÒªPOSTµÄURLÊý¾Ý +def postData = "https://sh.fangjia.com/zoushi?cityName=%E4%B8%8A%E6%B5%B7&keyword=%E5%A4%A9%E5%B1%B1%E6%96%B0%E8%8B%91" + +// ´´½¨URL¶ÔÏó +URL url = new URL(targetUrlString) + +// ´ò¿ªÁ¬½Ó +HttpURLConnection connection = (HttpURLConnection) url.openConnection() +connection.setDoOutput(true) // ±íÃ÷ÎÒÃǽ«·¢ËÍPOSTÇëÇóµÄÊä³öÊý¾Ý +connection.setRequestMethod("POST") // ÉèÖÃÇëÇó·½·¨ÎªPOST +connection.setRequestProperty("User-Agent", "curl/7.12.1") // ÉèÖÃUser-Agent£¬¾¡¹ÜÕâÔÚʵ¼ÊÓ¦ÓÃÖпÉÄܲ¢·Ç±ØÐè +connection.setRequestProperty("Content-Type", "text/plain") // ÉèÖÃÄÚÈÝÀàÐÍ£¬ÒòΪÎÒÃǽ«·¢ËÍ´¿Îı¾Êý¾Ý +connection.setRequestProperty("Content-Length", Integer.toString(postData.getBytes().length)) // ÉèÖÃÄÚÈݳ¤¶È + +// ·¢ËÍPOSTÊý¾Ý +//try (OutputStream os = connection.getOutputStream()) { +// byte[] input = postData.getBytes("utf-8") +// os.write(input, 0, input.length) +//} +outputStream = connection.getOutputStream(); +outputStream.write(postData.getBytes()); +outputStream.flush(); +outputStream.close(); + +// »ñÈ¡ÏìÓ¦Âë +int responseCode = connection.getResponseCode() +println "POST Response Code :: $responseCode" + +// ¿ÉÑ¡£º¶ÁÈ¡ÏìÓ¦ÄÚÈÝ +def reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8")) +StringBuilder response = new StringBuilder() +String responseLine +while ((responseLine = reader.readLine()) != null) { + response.append(responseLine.trim()) +} +println "Response Body :: ${response.toString()}" + +// ¹Ø±ÕÁ¬½Ó +connection.disconnect() \ No newline at end of file diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/AddDevShapeData.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/AddDevShapeData.groovy new file mode 100644 index 000000000..4df41ffc4 --- /dev/null +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/AddDevShapeData.groovy @@ -0,0 +1,202 @@ +package com.fangjia.script.gj.data_handle + +import com.fangjia.core.util.BaiDuApiUtils +import com.fangjia.core.util.ExcelUtil +import com.fangjia.core.util.GeoUtils +import com.fangjia.script.gj.district.FangjiaClientUtils +import com.fangjia.script.util.DateUtils +import com.fangjia.script.util.ExcelUtils +import com.fangjia.script.util.MongoUtils +import com.mongodb.BasicDBObject +import com.mongodb.DBCollection +import groovy.json.JsonSlurper +import groovy.io.FileType +import org.bson.types.ObjectId + +import java.util.regex.Pattern + +class AddDevShapeData { + + DBCollection DEVELOPMENT_ZONE_43_COLL = MongoUtils.getCollectionByName("fangjia_base", "development_zone", "mongo.db.fangjia.com") + + public static final def MONGO100_URL = "mongodb://admin:G00MONGOADMIN@192.168.0.100:30009"; + DBCollection dev_mapping_CONN = MongoUtils.getCollectionByName2("fangjia", "dev_mapping", MONGO100_URL) + + def devAreaMap = [:] + + static main(args) { + def task = new AddDevShapeData(); + task.run() +// task.streetInfo() + } + + def run(){ + def directoryPath = 'D:\\Êý¾Ý\\Êý¾Ý½¨Éè\\¿ª·¢ÇøÍâ°ü\\111¿ª·¢Çø\\' + def dir = new File(directoryPath) + if (dir.isDirectory()) { +// dir.eachFileRecurse(FileType.FILES) { file -> +// process(file.absolutePath) +// } + addDevInfo("D:\\Êý¾Ý\\Êý¾Ý½¨Éè\\¿ª·¢ÇøÍâ°ü\\ËùÓпª·¢Çø.xlsx") + } else { + println "The specified path is not a directory." + } + } + + def addDevInfo(file){ + ExcelUtils.multiThreadingModify(file, {d-> +// if(!d['I']){ + def name = d['D'] + def q = new BasicDBObject() + q.put('_id',new ObjectId(d['A'])) + def obj = DEVELOPMENT_ZONE_43_COLL.findOne(q) + if(obj){ + if(obj.operator){ + d['H'] = obj.operator + } + if(obj.operate_result){ + d['I'] = obj.operate_result + } + if(obj.m_date){ + d['P'] = DateUtils.formatDateByPattern(obj.m_date, "yyyy-MM-dd") + } + } +// } + devAreaMap.each {k,v-> + if(name.contains(k)){ + d['M'] = v.area_info + d['N'] = v.count + d['O'] = DateUtils.formatDateByPattern(new Date(), "yyyy-MM-dd") + } + } + }) + } + + def process(file){ + def retMap = getNewLocations(file) + if(retMap && retMap.gaode.size()>0){ + def q = new BasicDBObject() + q.put('name',new BasicDBObject('$regex', Pattern.compile('^.*'+retMap.name+'.*$', Pattern.CASE_INSENSITIVE))) + def obj = DEVELOPMENT_ZONE_43_COLL.findOne(q) + if(obj){ + for(def i=0;i0){ + obj.removeField("_id") + obj.put("create_time", new Date()) + obj.put("block", retMap.name+"-µØ¿é"+i) + obj.put("shape", resultMap) + obj.put("m_date", new Date()) + obj.put("bd_shape",bd_resultMap) + obj.put("operator", "Íâ°ü") + obj.put( "operate_result" , "ÒÑ´¦Àí") + DEVELOPMENT_ZONE_43_COLL.save(obj) + }else{ + udata.put("shape", resultMap) + udata.put("m_date", new Date()) + udata.put("bd_shape",bd_resultMap) + udata.put("operate_result" , "ÒÑ´¦Àí") + udata.put("operator", "Íâ°ü") + DEVELOPMENT_ZONE_43_COLL.update(q, new BasicDBObject('$set', udata), false, false) + } + } + } + } + } + + def getNewLocations(file){ + def jsonObj = readJson(file) + def features = jsonObj.features + def gaode_locations = [] + def baidu_locations = [] + def name = null + def areaMap = [:] + if(features && features.size()==1){ + name = features[0].properties.Name + def coordinates = features[0].geometry.coordinates + + def index = 0 + println name +" ÓÐ "+coordinates.size()+" ¿é" + + areaMap.count = coordinates.size() + def areas = [] + if(name.contains("ȪÖݾ­¼Ã¼¼Êõ¿ª·¢Çø")){ + for(def pointList : coordinates){ + index ++ + def gaode_coordinates = [] + def bd_coordinates = [] + def points = null + if(pointList.size()>1){ + points = pointList + }else{ + points = pointList[0] + } + double area = com.fangjia.script.util.GeoHelper.calculateArea(points) + println name +" µØ¿é"+index + "ΧÀ¸Ãæ»ýÊÇ: ${area} ƽ·½¹«Àï" + areas << area + def locationstr = "" + for(def arrs : points){ + def gaode_map = GeoUtils.gps84ToGcj02(arrs[1].toString().toDouble(), arrs[0].toString().toDouble()) + gaode_coordinates << [gaode_map.get("lng"), gaode_map.get("lat")] + + //´Ë¸ßµÂת°Ù¶È ÓÐÆ«²î + def bd_map = GeoUtils.gcj02ToBd09(gaode_map.get("lat"), gaode_map.get("lng")) +// bd_coordinates << [bd_map.get("lng"), bd_map.get("lat")] + // ¸ßµÂת°Ù¶È ͨ¹ý½Ó¿ÚÓдÎÊýÏÞÖÆ +// def baidu = BaiDuApiUtils.geoconv(gaode_map.get("lng"), gaode_map.get("lat"), 3) +// bd_coordinates << [baidu.x, baidu.y] + + locationstr = arrs[0].toString()+","+arrs[1].toString() + def bdpoint = FangjiaClientUtils.convert(locationstr.substring(0, locationstr.length()), 6) + if(bdpoint){ + bd_coordinates << bdpoint + } + } + //Õû¸öÒ»´®Ò»Æð´«³¬¹ý4029»á±¨´í +// bd_coordinates = FangjiaClientUtils.convert(locationstr.substring(0, locationstr.length()-1), 6) + gaode_locations << gaode_coordinates + if(bd_coordinates){ + baidu_locations << bd_coordinates + }else{ + println name +" ת»»ÓÐÎÊÌâ" + } + + } + areaMap.area_info = areas.join("\n") + } + + }else{ + println file +" Óжà¸ö" + } + + devAreaMap.put(name, areaMap) + def retMap = [:] + retMap.name = name + retMap.gaode = gaode_locations + retMap.baidu = baidu_locations + return retMap + } + + def readJson(def file){ + def jsonSlurper = new JsonSlurper() + def jsonFile = new File(file) + def jsonText = jsonFile.text + def jsonObj = jsonSlurper.parseText(jsonText) + return jsonObj + } + + def streetInfo(){ + ExcelUtils.multiThreadingModify("D:\\Êý¾Ý\\Êý¾Ý½¨Éè\\¿ª·¢ÇøÍâ°ü\\ËùÓпª·¢Çø.xlsx", {d-> + def count = dev_mapping_CONN.count(new BasicDBObject("name", d['E']).append("type", "ÏçÕò½ÖµÀ")) + d['L'] = count + }) + } +} diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/AddDistrictAddress.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/AddDistrictAddress.groovy new file mode 100644 index 000000000..977423309 --- /dev/null +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/AddDistrictAddress.groovy @@ -0,0 +1,448 @@ +package com.fangjia.script.gj.data_handle + +import com.fangjia.core.util.HttpRequest +import com.fangjia.script.BaseBatch +import com.fangjia.script.commData.CommonDatautils +import com.fangjia.script.common.DataHandleUtils +import com.fangjia.script.linxsh.util.AddressUtil +import com.fangjia.script.lixue.util.DBUtils +import com.fangjia.script.util.DbUtils +import com.fangjia.script.util.ExcelUtils +import com.fangjia.script.util.MongoUtils +import com.mongodb.BasicDBObject +import com.mongodb.DBCollection +import groovy.json.JsonSlurper +import net.sf.json.JSONObject + +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.CountDownLatch +import java.util.concurrent.ExecutorService +import java.util.concurrent.Executors +import java.util.concurrent.atomic.AtomicLong + +//²¹³ä¿âÖÐûÓÐÏêϸµØÖ·µÄÐ¡Çø +class AddDistrictAddress extends BaseBatch{ + +// def fullCityMap = CommonDatautils.queryFullNameCity() +// def mcaDistMap = CommonDatautils.queryDistNameCityByMapping() +// +// DBCollection BAIDU_POI_COLL = MongoUtils.getCollectionByName("crawl", "poi_wap_spider", "192.168.0.206",27020) +// public static final DBCollection seaweed_fence_coll = MongoUtils.getCollectionByName("fangjia_base", "seaweed_fence", "mongo.db.fangjia.com") +// +// +// public static final DBCollection administrative_mapping_coll = MongoUtils.getCollectionByName("business", "administrative_mapping", "mongo.db.fangjia.com") +// +// def MONGO100_URL = "mongodb://admin:G00MONGOADMIN@192.168.0.100:30009"; +// DBCollection seaweed_fence100_CONN = MongoUtils.getCollectionByName2("fangjia", "seaweed_fence", MONGO100_URL) +// +// public static ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10) + + static main(args) { + runBatch(new AddDistrictAddress(), args) + } + + @Override + public void process(Object args) { +// addNoAddressDist() //Ϊ²»¾«È·µÄµØÖ·Í¨¹ýµØÍ¼²¹³äµØÖ· +// mapOtherAddress() //Óо«È·µØÖ·µÄѰÕÒÆäËüµØÖ· + +// addressSelect() + addrUpdateToDB() + } + + + def addNoAddressDist(){ + // def citys = CommonDatautils.findAllCity() +// def index = 0 +// def allrets = [] +// for(def c : citys){ +// index ++ +// def districts = CommonDatautils.findAllDistricts(c, "district", ["city", "region", "name", "estate_type2", "address"]) +// def noRoadInfoDists = noDetailRoadInfoDistricts(districts) +// println c +" "+index +" Ô­Ê¼Ð¡ÇøÁ¿£º"+districts.size() +" ÐèÐÂÔöµØÖ·Á¿£º"+noRoadInfoDists.size() +// noRoadInfoDists = baiduMatch(c, noRoadInfoDists) +// noRoadInfoDists = gaodeMatch(c, noRoadInfoDists) +// +// def rets = [] +// rets << ["id", "³ÇÊÐ", "ÇøÓò", "Ãû³Æ", "µØÖ·", "°Ù¶ÈÔ­µØÖ·", "°Ù¶È±ê×¼µØÖ·", "¸ßµÂÔ­µØÖ·", "¸ßµÂ±ê×¼µØÖ·"] +// for(def d : noRoadInfoDists){ +// rets << [d._id.toString(), d.city, d.region, d.name, d.address, d.baidu_old_addr?d.baidu_old_addr:'',d.baidu_address?d.baidu_address:'', d.gaode_old_addr?d.gaode_old_addr:'', d.gaode_addr?d.gaode_addr:""] +// } +// allrets.addAll(rets) +// if(allrets.size()>50000){ +// ExcelUtils.write("D:\\Êý¾Ý\\Ð¡Çø\\Ð¡ÇøÄ£ºýµØÖ·²¹³ä"+index+".xlsx", allrets, "ÐÂÔöµØÖ·") +// allrets.clear() +// } +// } + updateDistAddr() + } + + + def mapOtherAddress(){ + def citys = CommonDatautils.findAllCity() + def index = 0 + def allrets = [] + for(def c : citys){ + index ++ + def districts = CommonDatautils.findAllDistricts(c, "district", ["city", "region", "name", "estate_type2", "address", "addr_alias"]) + def radInfoDists = haveRoadInfoDistricts(districts) + println c +" "+index +" Ô­Ê¼Ð¡ÇøÁ¿£º"+districts.size() +" ÓÐÏêϸµØÖ·Á¿£º"+radInfoDists.size() + radInfoDists = baiduMatch(c, radInfoDists) + radInfoDists = gaodeMatch(c, radInfoDists) + + def rets = [] + rets << ["id", "³ÇÊÐ", "ÇøÓò", "Ãû³Æ", "µØÖ·","µØÖ·±ðÃû", "°Ù¶ÈÔ­µØÖ·", "°Ù¶È±ê×¼µØÖ·", "¸ßµÂÔ­µØÖ·", "¸ßµÂ±ê×¼µØÖ·"] + for(def d : radInfoDists){ + def addr_alias_str = ''; + if(d.addr_alias){ + addr_alias_str = d.addr_alias.join(" ") + } + rets << [d._id.toString(), d.city, d.region, d.name, d.address, addr_alias_str,d.baidu_old_addr?d.baidu_old_addr:'',d.baidu_address?d.baidu_address:'', d.gaode_old_addr?d.gaode_old_addr:'', d.gaode_addr?d.gaode_addr:""] + } + allrets.addAll(rets) + if(allrets.size()>50000){ + ExcelUtils.write("D:\\Êý¾Ý\\Ð¡Çø\\Ð¡Çø¾«È·µØÖ·²¹³ä"+index+".xlsx", allrets, "²¹³äµØÖ·") + allrets.clear() + } + } + } + + def addressSelect(){ + ExcelUtils.multiThreadingModify("D:\\Êý¾Ý\\Ð¡Çø\\¾«È·µØÖ·²¹³ä-all-2.xlsx",{d-> + if(d['G']){ + d['O'] = AddressUtil.formatAddress(d['B'], d['G']) + } + if(d['I']){ + d['P'] = AddressUtil.formatAddress(d['B'], d['I']) + } + }) + } + + def addrUpdateToDB(){ + def updateDist = 0 + def addAddrCount = 0 + ExcelUtils.multiThreadingModify("D:\\Êý¾Ý\\Ð¡Çø\\¾«È·µØÖ·²¹³ä-Èë¿â-2.xlsx",{d-> + def dist = CommonDatautils.findDistrictById(d['A']) + if(dist){ + def oldAddrAliasCount = 0 + if(dist.addr_alias){ + oldAddrAliasCount = dist.addr_alias.size() + } + def new_addr_alias = null + if(d['K'].contains("ÐÂÔö°Ù¶ÈµØÖ·") || d['K'].contains("Ë«µØÍ¼ÐÂÔö")){ + new_addr_alias = getNewAddressAlias(d['L'], dist.address, dist.addr_alias) + } + if(d['K'].contains("ÐÂÔö¸ßµÂµØÖ·") || d['K'].contains("Ë«µØÍ¼ÐÂÔö")){ + new_addr_alias = getNewAddressAlias(d['M'], dist.address, dist.addr_alias) + } + if(new_addr_alias){ + updateDist++ + println updateDist + addAddrCount = addAddrCount + new_addr_alias.size()-oldAddrAliasCount + + def udata = new BasicDBObject() + udata.put("addr_alias", new_addr_alias) + udata.put("m_date", new Date()) + DbUtils.seaweed.update(new BasicDBObject('_id', dist._id),new BasicDBObject('$set',udata)) + } + } + }) + println "ÐÞ¸ÄÐ¡ÇøÊý£º"+updateDist + println "ÐÂÔöµØÖ·Êý£º"+addAddrCount + } + + def getNewAddressAlias(new_addr, old_addr, dist_addr_alias){ + def arrs = new_addr.split(";") + def addr_alias = [] + if(dist_addr_alias){ + addr_alias = dist_addr_alias + } + for(def address : arrs){ + if(old_addr!=address && !addr_alias.contains(address)){ + addr_alias << address + } + } + return addr_alias + } + + def updateDistAddr(){ + ExcelUtils.multiThreadingModify("D:\\Êý¾Ý\\Ð¡Çø\\´ýÐÂÔöÐ¡ÇøµØÖ·.xlsx",{d-> + def dist = CommonDatautils.findDistrictById(d['A']) + if(dist){ + def udata = new BasicDBObject() + udata.put("address", d['J']) + def addr_alias = dist.addr_alias + if(!dist.addr_alias){ + addr_alias = [] + } + if(d['K'] && !addr_alias.contains(d['K'])){ + addr_alias << d['K'] + } + + if(addr_alias){ + udata.put("addr_alias", addr_alias) + } + DbUtils.seaweed.update(new BasicDBObject('_id', dist._id),new BasicDBObject('$set',udata)) + d['L'] = "ÒѸüÐÂ" + } + }) + } + + def noDetailRoadInfoDistricts(districts){ + def rets = [] + for(def d : districts){ + if(d.address){ + def flag = DataHandleUtils.isStandardRoad(d.address) + if(!flag){ + rets << d + } + }else{ + rets << d + } + } + return rets; + } + + def haveRoadInfoDistricts(districts){ + def rets = [] + for(def d : districts){ + if(d.address){ + def flag = DataHandleUtils.isStandardRoad(d.address) + if(flag){ + rets << d + } + } + } + return rets; + } + + def baiduMatch(city,districts){ + def data = fullCityMap.get(city) + def fullCityName = null + if(data){ + fullCityName = data.city + } + final CountDownLatch latch = new CountDownLatch(districts.size()) + + if(fullCityName){ + def totalCount = new AtomicLong() + for(def i=0;i + def addrMap = nineAddrSplit(d['B'], d['E']) + def addrList = [] + if(addrMap && addrMap.address){ + d['G'] = addrMap.city + d['H'] = addrMap.address + addrList << addrMap.address + } + if(d['F']){ + def addrs = d['F'].split(",") + def addr_alias = [] + for(def addr : addrs){ + def map = nineAddrSplit(d['B'], addr) + if(map && map.address && DataHandleUtils.isStandardRoad(map.address)){ + if(!addrList.contains(map.address)){ + addrList << map.address + addr_alias << map.address + } + } + } + d['I'] = addr_alias.join(",") + } + }) + + } + + def nineAddrSplit(city, addr){ + def jsonObject = com.fangjia.script.gj.district.FangjiaClientUtils.formatNinelevel(city, addr) + def address = "" + def map = [:] + if (jsonObject) { + if (jsonObject.get("province") && jsonObject.get("province") != "null") { + map.province = jsonObject.get("province") + }else{ + map.province = "" + } + if (jsonObject.get("city") && jsonObject.get("city") != "null") { + map.city = jsonObject.get("city") + }else{ + map.city = "" + } + if (jsonObject.get("district") && jsonObject.get("district") != "null") { + map.district = jsonObject.get("district") + }else{ + map.district = "" + } + if (jsonObject.get("street") && jsonObject.get("street") != "null") { + address = jsonObject.get("street") + } + if (jsonObject.get("streetNumber") && jsonObject.get("streetNumber") != "null") { + address = address + jsonObject.get("streetNumber") + } + map.address = address + } + return map + } + + def run(){ + def citys = CommonDatautils.findAllCity() + def rows = [] + citys.each{c-> + def districts = CommonDatautils.findAllDistricts(c, "district", ["city","region", "name","address", "addr_alias"]) + println c +" "+districts.size() + def num = 0 + for(def d : districts){ + num++ + def row = [num, d.city, d.region, d.name, d.address] + if(d.addr_alias){ + row << d.addr_alias.join(",") + } + rows << row + } + } +// ExcelUtils.write("D:\\Êý¾Ý\\Êý¾Ý½¨Éè\\Ð¡Çø\\Ð¡ÇøµØÖ·¼°µØÖ·±ðÃû±ê×¼»¯.xlsx", rows, "Ð¡Çø") + FileUtils.batchCreateFileByCustomSuffix(rows, "D:\\Êý¾Ý\\Êý¾Ý½¨Éè\\Ð¡Çø\\Ð¡ÇøµØÖ·¼°µØÖ·±ðÃû±ê×¼»¯.bat", null, "utf-8", false, "#",""); + } +} diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/AutoAddDistrictBatch.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/AutoAddDistrictBatch.groovy index 809fa216c..9d223e038 100644 --- a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/AutoAddDistrictBatch.groovy +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/AutoAddDistrictBatch.groovy @@ -35,22 +35,22 @@ class AutoAddDistrictBatch extends BaseBatch{ @Override void process(Object args) { -// //²éÕÒµÚÈý·½Æ¥ÅäûÓÐÆ¥ÅäÉϵÄÐ¡Çø -// def citys = CommonDatautils.findAllCity() -// def list = [] -// list << ["³ÇÊÐ", "ÇøÓò", "Ãû³Æ", "³É½»Á¿", "·¿Ô´Á¿", "°Ù¶ÈµØÍ¼", "°Ù¶ÈÀàÐÍ","¸ßµÂµØÍ¼", "¸ßµÂÀàÐÍ"] -// for(def c : citys){ -// def noMatchDatas = findNoMatchResult(c) -// println c +" оÉË㷨δƥÅäµÄÊý¾ÝÁ¿£º"+noMatchDatas.size() -// def rets = checkDatas(noMatchDatas.keySet()) -// list.addAll(rets) -// } + //²éÕÒµÚÈý·½Æ¥ÅäûÓÐÆ¥ÅäÉϵÄÐ¡Çø + def citys = CommonDatautils.findAllCity() + def list = [] + list << ["³ÇÊÐ", "ÇøÓò", "Ãû³Æ", "³É½»Á¿", "·¿Ô´Á¿", "°Ù¶ÈµØÍ¼", "°Ù¶ÈÀàÐÍ","¸ßµÂµØÍ¼", "¸ßµÂÀàÐÍ"] + for(def c : citys){ + def noMatchDatas = findNoMatchResult(c) + println c +" оÉË㷨δƥÅäµÄÊý¾ÝÁ¿£º"+noMatchDatas.size() + def rets = checkDatas(noMatchDatas.keySet()) + list.addAll(rets) + } def fileName = "/home/goojia/gj/add_dist_info.xlsx" if (CommonDatautils.isWindow()) { fileName = "D:\\Êý¾Ý\\add_dist_info_1.xlsx" } -// ExcelUtils.write(fileName, list, "´ýÈë¿âÊý¾Ý") + ExcelUtils.write(fileName, list, "´ýÈë¿âÊý¾Ý") check(fileName) diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/BusinessQuarterProcess.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/BusinessQuarterProcess.groovy new file mode 100644 index 000000000..f122be3c0 --- /dev/null +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/BusinessQuarterProcess.groovy @@ -0,0 +1,268 @@ +package com.fangjia.script.gj.data_handle + +import com.fangjia.core.RegionData +import com.fangjia.script.commData.CommonDatautils +import com.fangjia.script.common.DataHandleUtils +import com.fangjia.script.gj.district.FangjiaClientUtils +import com.fangjia.script.gj.xiamen.ElasticUtils89 +import com.fangjia.script.lixue.util.DBUtils +import com.fangjia.script.looplineinfo.InsidePolygon +import com.fangjia.script.util.DbUtils +import com.fangjia.script.util.ElasticUtils +import com.fangjia.script.util.MongoUtils +import com.mongodb.BasicDBObject +import com.mongodb.DBCollection +import org.bson.types.ObjectId +import org.elasticsearch.action.bulk.BulkRequest +import org.elasticsearch.action.bulk.BulkResponse +import org.elasticsearch.action.index.IndexRequest +import org.elasticsearch.action.support.WriteRequest +import org.elasticsearch.action.update.UpdateRequest +import org.elasticsearch.client.RequestOptions +import org.elasticsearch.common.xcontent.XContentType + +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.CountDownLatch +import java.util.concurrent.ExecutorService +import java.util.concurrent.Executors +import java.util.concurrent.atomic.AtomicLong + +class BusinessQuarterProcess { + + def regionMap = com.fangjia.script.commData.CommonDatautils.queryAllRegionNameByCity() + def fullCityMap = CommonDatautils.queryFullNameCity() + DBCollection bk_map_bussiness_COLL = MongoUtils.getCollectionByName("crawl", "bk_map_sq", "192.168.0.206",27020) + + public static final DBCollection bk_business_coll = MongoUtils.getCollectionByName("fangjia_base", "bk_business", "mongo.db.fangjia.com") + + public static ExecutorService fixedThreadPool = Executors.newFixedThreadPool(20) + + static main(args) { + def task = new BusinessQuarterProcess() + task.run() + } + def run(){ +// synchBusinessData() +// updateBusinessQuarter() +// addRegion() + synchBusinessToEs() + } + + def addRegion(){ + def list = CommonDatautils.queryRangeByCat("ÇøÓò") + println list.size() + def dbcursor = bk_business_coll.find(new BasicDBObject("_id", new ObjectId("67a318893b75f388c80979f2"))) + for(def d : dbcursor){ + if(d.district){ + continue + } + for(def regionShape : list){ + if(d.short_city!=regionShape.city_short){ + continue + } + def flag = InsidePolygon.isInArea(d.location.lon, d.location.lat, InsidePolygon.createPoint4(regionShape.shape.coordinates)) + if(flag){ + def udata = new BasicDBObject() + udata.put("district", regionShape.mzb_district_name) + udata.put("short_district", regionShape.district_short) + bk_business_coll.update(new BasicDBObject("_id", d._id), new BasicDBObject('$set', udata)) + break + } + } + } + } + + def synchBusinessData(){ + def datas = bk_map_bussiness_COLL.find(new BasicDBObject("type", null)).toList() + synchMongoProcess(datas) + + } + + def synchMongoProcess(datas){ + def totalCount = new AtomicLong() + final CountDownLatch latch = new CountDownLatch(datas.size()) + for(def i=0;i=100){ +// updateByEs(rows) +// rows.clear() +// } + updateByEs(d, index) + } + } + + def updateByEs(row, index){ + BulkRequest request = new BulkRequest(); + def client = ElasticUtils89.getClient("192.168.0.89") + int processedCount = 0; + + def id = row.get("_id").toString() + def doc = [:] + doc.put("province",row.province) + doc.put("short_province",row.short_province) + doc.put("city",row.city) + doc.put("short_city",row.short_city) + doc.put("district",row.district) + doc.put("short_district",row.short_district) + doc.put("name", row.name) + doc.put("location", row.location) + doc.put("bd_location", row.bd_location) + doc.put("shape", row.shape) + doc.put("bd_shape", row.bd_shape) + + + request.add(new IndexRequest("bk_business", "_doc", id).source(doc, XContentType.JSON)); + if (request.numberOfActions() >= 0) { + request.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); + BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT); + if (bulkResponse.hasFailures()) { + // ´¦Àí´íÎó + println "[${index}] Bulk request has failures: " + bulkResponse.buildFailureMessage() + } else { + processedCount += request.numberOfActions(); +// println "Processed " + processedCount + " documents" + } + } + + } +} diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/DevProcess.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/DevProcess.groovy index acf416bff..a6503133c 100644 --- a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/DevProcess.groovy +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/DevProcess.groovy @@ -72,7 +72,7 @@ class DevProcess { // println DateUtils.add("2024-7-24", 7); // task.addKfc() -// task.devToPark() //¿ª·¢ÇøÏÂÏ½Ô°Çø +// task.devToPark() //¿ª·¢ÇøÏÂϽ԰ // task.checkTown() // task.repeatSave() @@ -84,6 +84,7 @@ class DevProcess { // task.addQiDevResult() //»ñÈ¡ÆëÁºÊý¾Ý½á¹û // task.updateDevShape()//Ð޸Ŀª·¢Çø½á¹¹ + } @@ -439,30 +440,33 @@ class DevProcess { } def matchDev(){ - ExcelUtils.multiThreadingModify("D:\\Êý¾Ý\\Êý¾Ý½¨Éè\\¿ª·¢Çø\\ÐÂÅÜÊ¡·Ý\\½­ËÕÊ¡\\½­ËÕÊ¡-ÆëÁº´ýÅܵØÖ·.xlsx",{d-> - if(!d['B'] && d['A']){ + ExcelUtils.multiThreadingModify("D:\\Êý¾Ý\\Êý¾Ý½¨Éè\\¿ª·¢Çø\\¸ßÐÂÇø.xls",{d-> + if(!d['E'] && d['D']){ def q = new BasicDBObject() -// q.put("name", d['A']) -// q.put("city",d['G']) -// q.put('alias', new BasicDBObject('$in',[d['A']])) - def name = d['A'].replace('¾­¼Ã¼¼Êõ¿ª·¢Çø','¾­¼Ã¿ª·¢Çø') +// q.put("name", d['D']) + q.put("city",d['C']) +// q.put('alias', new BasicDBObject('$in',[d['D']])) + def name = d['D'] //.replace('¾­¼Ã¼¼Êõ¿ª·¢Çø','¾­¼Ã¿ª·¢Çø') q.put('name',new BasicDBObject('$regex', Pattern.compile('^.*'+name+'.*$', Pattern.CASE_INSENSITIVE))) //Ãû³Æ Ä£ºý²éѯ def obj = development_zone_CONN.findOne(q) if(obj){ - d['I'] = "¿âÖÐÓпª·¢Çø-ÏàËÆ2" + d['G'] = "ÏàËÆ" // d['K'] = obj.name // d['C'] = obj._id.toString() - d['B'] = obj.name -// if(obj.name == d['A']){ -// d['E'] = "Ïàͬ" + d['E'] = obj.name +// if(obj.name == d['D']){ +// d['G'] = "Ïàͬ" // }else{ -// d['E'] = "°üº¬" +// d['G'] = "°üº¬" // } + if(obj.shape){ + d['F'] = "ÊÇ" + } // d['E'] = "±ðÃû" // d['F'] = obj.name } } - },1); + },0); } def calAddrDistince(){ diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/DevQlCheck.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/DevQlCheck.groovy new file mode 100644 index 000000000..f37e917d2 --- /dev/null +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/DevQlCheck.groovy @@ -0,0 +1,113 @@ +package com.fangjia.script.gj.data_handle + +import com.fangjia.core.util.ExcelUtil +import com.fangjia.script.gj.ProxyHttpUtils +import com.fangjia.script.looplineinfo.InsidePolygon +import com.fangjia.script.util.ExcelUtils +import com.fangjia.script.util.MongoUtils +import com.mongodb.BasicDBObject +import com.mongodb.DBCollection +import net.sf.json.JSONObject +import org.apache.commons.io.FileUtils + +class DevQlCheck { + + //http://146.56.217.44:8088/uams/index + String targetUrl = "http://146.56.217.44:9010/uams/farmer/all/v3/sign"; + DBCollection DEVELOPMENT_ZONE_43_COLL = MongoUtils.getCollectionByName("fangjia_base", "development_zone", "mongo.db.fangjia.com") + + static main(args) { + def task = new DevQlCheck() + task.run() + } + + def run(){ + def devName = "¸£½¨Áúº£¾­¼Ã¿ª·¢Çø" + def obj = DEVELOPMENT_ZONE_43_COLL.findOne(new BasicDBObject("name",devName)) + def pois = readCSV("C:\\Users\\gaojuan\\Downloads\\ÕÄÖÝÊÐPOI.csv") + def devPois = [] + devPois << ["Ê¡", "³ÇÊÐ", "ÇøÓò", "Ãû³Æ", "µØÖ·", "ÀàÐÍ", "¾­¶È", "γ¶È", "ÆëÁº¿ª·¢Çø"] + for(def poi : pois){ + def flag = InsidePolygon.isInArea(poi.lng.toString().toDouble(), poi.lat.toString().toDouble(), InsidePolygon.createPoint4(obj.shape.coordinates)) + if(flag){ + devPois << [poi.province, poi.city, poi.district, poi.name, poi.address, poi.cat, poi.lng, poi.lat] + } + } + println "¹²£º"+devPois.size()+" ¸ö" + ExcelUtils.write("D:\\Êý¾Ý\\Êý¾Ý½¨Éè\\¿ª·¢ÇøÍâ°ü\\${devName}poiÆëÁºÐ£Ñé.xlsx", devPois, "ÆëÁº¿ª·¢Çø") + def index = 0 + ExcelUtils.modify("D:\\Êý¾Ý\\Êý¾Ý½¨Éè\\¿ª·¢ÇøÍâ°ü\\${devName}poiÆëÁºÐ£Ñé.xlsx",{d-> + def address = d['B']+d['C']+d['D'] +// if(d['E']){ +// address = address + d['E'] +// } + Thread.sleep(3000) + def s = getQlResult(address) + d['I'] = s + index ++ + println index+" "+ s + }) + + + } + + def getQlResult(address){ + def params = [ + 'address': address, + 'type': '1' //1£º¶Ô¹« 0£º¶Ô˽ + ] + try{ + def str = ProxyHttpUtils.getProxyResult(targetUrl, params); + println address +" "+ str + JSONObject result = JSONObject.fromObject(str) + if(result && result.code==20000){ + def data = result.data + if(data){ + def list = data.indusParkList + if(list && list!="null"){ + def s = "" + for(def r : list){ + s = s + r.indusParkName +"-"+r.indusParkLevel+"\n" + } + return s + } + } + } + }catch(Exception e){ + println address +" "+e.getMessage() + } + + return null + } + + + def readCSV(filename){ + def lines = FileUtils.readLines(new File(filename)) + def rets = []; + for(line in lines) { + if(line){ + String[] arrs = line.split("\\|@\\|") + def o = new BasicDBObject() + try{ + o.put("province", arrs[0]) + o.put("city", arrs[1]) + o.put("district", arrs[2]) + o.put("name", arrs[3]) + o.put("township", arrs[4]) + o.put("address", arrs[5]) + o.put("cat", arrs[6]) + o.put("lng", arrs[7]) + o.put("lat", arrs[8]) + o.put("data_source", arrs[9]) + rets << o + }catch(Exception e){ + println filename+" ÎļþÒì³£" + } + + } + + } + return rets; + } + +} diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/DevUpdateTestBatch.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/DevUpdateTestBatch.groovy index aaf80284e..50ec412b8 100644 --- a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/DevUpdateTestBatch.groovy +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/DevUpdateTestBatch.groovy @@ -32,7 +32,7 @@ class DevUpdateTestBatch { static main(args) { def task = new DevUpdateTestBatch() - def path = "D:\\Êý¾Ý\\¿ª·¢Çø-Ô°Çø.xlsx"//¿ª·¢Çø-Ô°Çø.xlsx + def path = "D:\\Êý¾Ý\\Êý¾Ý½¨Éè\\¿ª·¢Çø\\¿ª·¢Çø-Ô°Çø.xlsx"//¿ª·¢Çø-Ô°Çø.xlsx // task.addDev(path) task.addDevAddress(path) // @@ -167,7 +167,7 @@ class DevUpdateTestBatch { println d['A'] +" ²»´æÔÚ" } } - },0) + },1) } diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/GXDdistrictMatch.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/GXDdistrictMatch.groovy index ee54817e6..8a5fc6eec 100644 --- a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/GXDdistrictMatch.groovy +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/GXDdistrictMatch.groovy @@ -1,12 +1,14 @@ package com.fangjia.script.gj.data_handle import com.fangjia.core.RegionData +import com.fangjia.core.util.BaiDuApiUtils import com.fangjia.script.ccbevaluation.CcbCommonUtils import com.fangjia.script.ccbevaluation.PgsqlCommUtils import com.fangjia.script.commData.CommonDatautils import com.fangjia.script.gj.EsSearchUtils import com.fangjia.script.gj.district.FangjiaClientUtils import com.fangjia.script.linxsh.util.AddressUtil +import com.fangjia.script.util.DateUtils import com.fangjia.script.util.DbUtils import com.fangjia.script.util.ElasticUtils import com.fangjia.script.util.ExcelUtils @@ -28,14 +30,24 @@ class GXDdistrictMatch { static main(args) { def task = new GXDdistrictMatch(); // task.run() - task.addOldMatch2() +// task.addOldMatch2() // task.runDb() +// task.hainanMatch() // task.updateDistStatus()//»Ö¸´name_cat²»Õý³£Êý¾Ý // task.saveToDB() //±£´æÐÂÔöÐ¡Çø // task.restoreDist()//»Ö¸´Ð¡Çøstatus=0 // task.runMatch() + +// task.checkDist() + + task.addPrice() + + } + + def addPrice(){ + addPrice(row['K'],row['L'],row['M'], row['T'], DateUtils.parseFromTightByPattern('2023-10-01','yyyy-MM-dd'),DateUtils.parseFromTightByPattern('2023-10-25','yyyy-MM-dd')) } def addOldMatch(){ @@ -94,6 +106,46 @@ class GXDdistrictMatch { } + def hainanMatch(){ + def fileName = "D:\\Êý¾Ý\\Ð¡Çø\\º£ÄÏδƥÅ䵨ַ-1.xlsx" + ExcelUtils.multiThreadingModify(fileName, { d -> + if(d['D'] && d['F'] ){// +// def jsonObject = com.fangjia.script.gj.district.FangjiaClientUtils.formatNinelevel(null, d['I']) +// if(jsonObject){ +//// if(jsonObject.get("district") && jsonObject.get("district")!='null'){ +//// d['AO'] = jsonObject.get("district") +//// } +// if(jsonObject.get("province") && jsonObject.get("province")!="null"){ +// d['AP'] = jsonObject.get("province") +// } +// if(jsonObject.get("city") && jsonObject.get("city")!="null"){ +// d['AI'] = jsonObject.get("city") +// } +// } + def formatCity = RegionData.formatCity(d['F']) + def fullCityObj = fullCityMap.get(formatCity) + if(fullCityObj){ +// def fullRegion = regionCodeDataMap.get(d['A']+"#"+d['E']) + + def obj = findDatasByCityAndName(formatCity, d['D'].replaceAll('[¡¤\\(\\)£¨£©]|¡¤', '')) + if(obj){ + d['U'] = "Â¥ÅÌץȡ¿â" + d['V'] = obj.city + d['W'] = obj.region + d['X'] = obj.name + d['Y'] = obj.property_type + d['Z'] = obj.address + def loc = obj.location + if(loc){ + d['AA'] = loc.x + d['AB'] = loc.y + } + } + } + } + }) + } + def runDb(){ def fileName = "D:\\Êý¾Ý\\¹úÐÅ´ï\\¹úÐÅ´ï11³ÇδƥÅäÊý¾Ý.xlsx" ExcelUtils.modify(fileName, { d -> @@ -238,43 +290,41 @@ class GXDdistrictMatch { def saveToDB(){ // def fileName = "D:\\Êý¾Ý\\¹úÐÅ´ï\\¹úÐÅ´ï11³ÇδƥÅäÊý¾Ý.xlsx" - def fileName = "D:\\Êý¾Ý\\Êý¾Ý½¨Éè\\Ð¡Çø\\¶«Ý¸Î´Æ¥Åä³É½»Êý¾Ý.xlsx" + def fileName = "D:\\Êý¾Ý\\Ð¡Çø\\º£ÄÏÐÂÔöÐ¡Çø.xlsx" ExcelUtils.modify(fileName, { d -> - if(d['A']){ + if(d['A'] && d['C']){ def udata = new BasicDBObject() udata.put("city", d['A']) udata.put("region", d['B']) def name = d['C'].replaceAll('[¡¤\\(\\)£¨£©]|¡¤', '').replace("½¨ÉèÖÐ", "") udata.put("name", name) - def alias = [] - if(d['G'] && name!=d['G']){ - alias << d['G'] - } +// def alias = [] +// if(d['G'] && name!=d['G']){ +// alias << d['G'] +// } // if(d['AI'] && !alias.contains(d['AI']) && d['AI']!=name){ // alias << d['AI'] // } - if(alias){ - udata.put("alias", alias) - } +// if(alias){ +// udata.put("alias", alias) +// } - def addr = AddressUtil.formatAddress(d['A'], d['D']) + def addr = AddressUtil.formatAddress(d['A'], d['E']) if(addr){ udata.put("address", addr) } - udata.put("status", "0") - udata.put("name_cat", "0") + udata.put("status", 0) + udata.put("name_cat", 0) udata.put("cat", "district") - udata.put("username", "¸ß¾ê") +// udata.put("username", "¸ß¾ê") def estateType2 = "ÆÕͨסլ" def type = "" -// if(d['AH']){ -// type = d['AH'] -// }else{ -// type = d['Y'] -// } + if(d['D']){ + type = d['D'] + } if(type){ if(type.contains("±ðÊû")){ estateType2 = "±ðÊû" @@ -282,26 +332,50 @@ class GXDdistrictMatch { estateType2 = "ÉÌס" } } - udata.put("estateType2", estateType2) + udata.put("estate_type2", estateType2) + if(d['F']){ Long lng = d['F']*10000000000 - udata.put("lng", lng) - } - if(d['E']){ - Long lat = d['E'] * 10000000000 + Long lat = d['G'] * 10000000000 udata.put("lat", lat) - } - - def s = FangjiaClientUtils.saveOrUpdateDistrict(udata) - def opt = "add" - if(s && s=='³É¹¦'){ - saveOptLog(udata.city, udata.region, udata.name, opt) + udata.put("lng", lng) + // ¸ßµÂת°Ù¶È + def baidu = BaiDuApiUtils.geoconv(d['F'].toString().toDouble(), d['G'].toString().toDouble(), 3) + def lng2 = baidu.x + def lat2 = baidu.y + if(lng2){ + Long lng2_new = lng2 *10000000000L + Long lat2_new = lat2 *10000000000L + udata.put("lng2", lng2_new) + udata.put("lat2", lat2_new) } } + udata.put("c_date", new Date()) + udata.put("m_date", new Date()) + def markMap = [:] + markMap.put("data_source", "»úÆ÷Èë¿â") + udata.put("mark_map",markMap) +// udata.put("is_new", 0) + DbUtils.seaweed.save(udata) + saveOptLog(udata.city, udata.region, udata.name, "add") +// def s = FangjiaClientUtils.saveOrUpdateDistrict(udata) + println name +// def opt = "add" +// if(s && s=='³É¹¦'){ +// saveOptLog(udata.city, udata.region, udata.name, opt) +// } + } }) } + def checkDist(){ + ExcelUtils.multiThreadingModify("D:\\Êý¾Ý\\Ð¡Çø\\º£ÄÏδƥÅ䵨ַ-1.xlsx", { d -> + if(d['V'] && d['W'] && d['X']){ + matching(d['V'], d['W'], d, d['X'], null, null) + } + }) + } def match(city, region, d){ d = matching(city, region, d, d['C'].replaceAll('[¡¤\\(\\)£¨£©]|¡¤', ''), d['D'], "") @@ -391,7 +465,7 @@ class GXDdistrictMatch { if(rets && rets.size()>=1){ d = setRowValue(rets[0], d, "Ãû³ÆÔÚµØÖ·ÖÐ"+str) }else{ - if (d['D']) { + if (d['D'] && alias) { rets = CommonDatautils.findDistrictByAlias(city, region, alias.replaceAll('[¡¤\\(\\)£¨£©]|¡¤', ''), "district") if (rets) { if (rets.size() >= 1) { @@ -449,14 +523,14 @@ class GXDdistrictMatch { def setRowValue(dbo, d, remark){ if (dbo) { - d['V'] = dbo.city - d['W'] = dbo.region - d['X'] = dbo.name - d['Y'] = dbo.estate_type2 - d['Z'] = dbo.status - d['AA'] = dbo.name_cat - d['U'] = remark - d['AH'] = dbo.address +// d['V'] = dbo.city +// d['W'] = dbo.region +// d['X'] = dbo.name +// d['Y'] = dbo.estate_type2 + d['AK'] = dbo.status +// d['AA'] = dbo.name_cat + d['AJ'] = remark +// d['AH'] = dbo.address } return d; } @@ -510,6 +584,33 @@ class GXDdistrictMatch { return null; } + + def findDatasByCityAndName(def city, def name){ + def sql = "select * from community where city='${city}' and name='${name}'" + def rets = [] + ElasticUtils.executeSqlQuery(sql, { d-> + rets << d + println d.property_type + }) + + if(rets){ + def obj = null + for(def r : rets){ + if(r.property_type && (r.property_type.contains("סլ") || r.property_type.contains("±ðÊû") || r.property_type.contains("¹«Ô¢"))){ + obj = r + break + } + } + if(obj){ + return obj; + }else{ + return rets[0]; + } + + } + return null; + } + def saveOptLog(city, region, name, type){ def obj = new BasicDBObject(); obj.put("city",city); diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/NewGaoDePoiBatch.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/NewGaoDePoiBatch.groovy index 822eee441..ea28d2c0b 100644 --- a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/NewGaoDePoiBatch.groovy +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/NewGaoDePoiBatch.groovy @@ -1,5 +1,6 @@ package com.fangjia.script.gj.data_handle +import com.fangjia.core.util.GeoUtils import com.fangjia.script.BaseBatch import com.fangjia.script.BatchOwner import com.fangjia.script.Watcher @@ -8,13 +9,19 @@ import com.fangjia.script.common.DataHandleUtils import com.fangjia.script.gj.xiamen.ElasticUtils89 import com.fangjia.script.looplineinfo.InsidePolygon import com.fangjia.script.util.ExcelUtils +import com.fangjia.script.util.ProvinceData +import com.mongodb.BasicDBObject +import org.apache.commons.io.FileUtils import org.elasticsearch.action.bulk.BulkRequest import org.elasticsearch.action.bulk.BulkResponse import org.elasticsearch.action.index.IndexRequest import org.elasticsearch.action.support.WriteRequest import org.elasticsearch.client.RequestOptions import org.elasticsearch.common.xcontent.XContentType +import org.elasticsearch.index.query.QueryBuilder +import org.elasticsearch.index.query.QueryBuilders +import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.CopyOnWriteArrayList import java.util.concurrent.CountDownLatch import java.util.concurrent.ExecutorService @@ -39,12 +46,13 @@ class NewGaoDePoiBatch extends BaseBatch{ @Override void process(Object args) { - run() +// run() + oldPoiMagre() } def run(){ if (CommonDatautils.isWindow()) { - TAGS = getAllPoiType("D:\\Êý¾Ý\\¸£½¨Ê¡_POI_GCJ02_20240630\\POI·ÖÀà°×Ãûµ¥.xlsx") + TAGS = getAllPoiType("D:\\Êý¾Ý\\Êý¾Ý½¨Éè\\Poi\\POI·ÖÀà°×Ãûµ¥.xlsx") }else{ TAGS = getAllPoiType("/home/goojia/gj/POI_TYPES.xlsx") } @@ -145,6 +153,7 @@ class NewGaoDePoiBatch extends BaseBatch{ saveObj.data_id = map.map_id saveObj.data_source = "¸ßµÂµØÍ¼" saveObj.data_source_year = "2024-11" + saveObj.parent_id = map.parent_id if(saveObj.cat && TAGS.contains(saveObj.cat)){ saveObj.status = 0 @@ -314,7 +323,7 @@ class NewGaoDePoiBatch extends BaseBatch{ rows.each{map-> // def map = rows.get(key) - request.add(new IndexRequest("didata_map_poi_2024", "_doc", map.data_id).source(map, XContentType.JSON)); + request.add(new IndexRequest("map_poi_2024", "_doc", map.data_id).source(map, XContentType.JSON)); // ÅúÁ¿Ìá½»Êý¾Ý if (request.numberOfActions() >= batchSize) { @@ -346,4 +355,177 @@ class NewGaoDePoiBatch extends BaseBatch{ } + def oldPoiMagre(){ + def cityList = CommonDatautils.findFullNameCitys().reverse() + def index = 0 + for(def cityObj : cityList){ + index ++ + if(index <291){ + continue + } + def fileName = "/home/goojia/gj/poi/old_poi/merge_poi/${cityObj.city}.csv" + if (CommonDatautils.isWindow()) { + fileName = "D:\\Êý¾Ý\\merge_poi\\${cityObj.city}.csv" + } + println fileName + File file=new File(fileName); + if(file.exists()){ + def results = readCSV(fileName) + println "ÔËÐгÇÊУº"+cityObj.province+" " +cityObj.city+" "+results.size() + if(results){ + def megerMap = poiRepeat(cityObj.city, results) + println "´ý±£´æ£º" + cityObj.city +" "+megerMap.size() + save(megerMap.values()) + } + }else{ + println fileName +" ²»´æÔÚ" + } + } + } + + + def poiRepeat(city, oldPois){ + def rets = new ConcurrentHashMap() + + def totalCount = new AtomicLong() + final CountDownLatch latch = new CountDownLatch(oldPois.size()) + def townMap = CommonDatautils.queryTownByCity(city) + def esMap = findEsPoiByCity(city) + + println "Es ¼ÓÔØÍê³É£º"+new Date().format("yyyy-MM-dd HH:mm:ss") + for(def i=0;i + def district = "¼ÎÓø¹ØÊÐ" + if(d.district){ + district = d.district + } + def regionMap = map.get(district) + if(!regionMap){ + regionMap = new HashMap() + } + def o = new BasicDBObject() + o.put("city", d.city) + o.put("district", district) + o.put("name", d.name) + o.put("township", d.township) + o.put("location", d.location) + regionMap.put(d.name.replace("-","").replace("¡¤",""), o) +// map.put(district, regionMap) + map.put(district, regionMap) + }) + return map + } + + + def readCSV(filename){ + def lines = FileUtils.readLines(new File(filename)) + def rets = []; + for(line in lines) { + if(line){ + String[] arrs = line.split("\\|@\\|") + def o = new BasicDBObject() + o.put("province",arrs[0]) + o.put("city" , arrs[1]) + o.put("district",arrs[2]) + o.put("name",arrs[3]) + o.put("township",arrs[4]) + o.put("address",arrs[5]) + o.put("cat",arrs[6]) + o.put("type",arrs[7]) + o.put("secondary_type",arrs[8]) + o.put("small_type" ,arrs[9]) + if(arrs[10]){ + o.put("data_id",arrs[10]) + }else{ + o.put("data_id",arrs[11]) + } + + o.put("spell_name",arrs[12]) + def location = [:] + if(arrs[13]){ + location.lon = arrs[13].toString().toDouble() + location.lat = arrs[14].toString().toDouble() + } + o.put("location",location) + o.put("data_source",arrs[15]) + o.put("status",arrs[16]) + o.put("version",arrs[17]) + rets << o + } + } + return rets; + } + } diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/PoiNineSplitBatch.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/PoiNineSplitBatch.groovy index 21432c057..bf7a84c06 100644 --- a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/PoiNineSplitBatch.groovy +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/PoiNineSplitBatch.groovy @@ -6,7 +6,7 @@ import com.fangjia.script.util.ExcelUtils class PoiNineSplitBatch{ - static main(args) { + public static void main(args) { def task = new PoiNineSplitBatch() task.run() } diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/ThirdPriceMappingBatch.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/ThirdPriceMappingBatch.groovy index a6180d973..7560c83ef 100644 --- a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/ThirdPriceMappingBatch.groovy +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/ThirdPriceMappingBatch.groovy @@ -52,9 +52,6 @@ class ThirdPriceMappingBatch extends BaseBatch{ def index = 0 for(def c : citys){ index ++ - if(index < 206){ - continue - } def query = new BasicDBObject("city", c).append("match_id", new BasicDBObject('$exists', false)) def noMatchDatas = thirdSeaweedMappingColl.find(query).toList() matchByCity(c, noMatchDatas) @@ -123,9 +120,6 @@ class ThirdPriceMappingBatch extends BaseBatch{ def index = 0 for(def c : citys){ index ++ - if(index < 70){ - continue - } def crawlDatas = thirdPartyPriceColl.find(new BasicDBObject("city", c).append("s_date", curDate)).toList() def addCount = addDatasToDB(crawlDatas) println c + " ÐÂÔö£º"+ addCount diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/TownStandardBatch.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/TownStandardBatch.groovy index 4d3e00e32..69c368290 100644 --- a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/TownStandardBatch.groovy +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/TownStandardBatch.groovy @@ -3,15 +3,29 @@ package com.fangjia.script.gj.data_handle import com.fangjia.script.BaseBatch import com.fangjia.script.commData.CommonDatautils import com.fangjia.script.gj.xiamen.ElasticUtils89 +import com.fangjia.script.looplineinfo.InsidePolygon +import com.fangjia.script.util.BaiduMapUtils +import com.fangjia.script.util.ElasticUtils import com.fangjia.script.util.ExcelUtils +import com.fangjia.script.yinjihaun.amap.GaoDeApiUtils import com.mongodb.BasicDBObject import org.apache.commons.io.FileUtils import org.elasticsearch.action.bulk.BulkRequest +import org.elasticsearch.action.bulk.BulkResponse +import org.elasticsearch.action.index.IndexRequest +import org.elasticsearch.action.support.WriteRequest import org.elasticsearch.action.update.UpdateRequest import org.elasticsearch.client.RequestOptions import org.elasticsearch.common.xcontent.XContentType import org.elasticsearch.index.query.QueryBuilder import org.elasticsearch.index.query.QueryBuilders + +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.CountDownLatch +import java.util.concurrent.ExecutorService +import java.util.concurrent.Executors +import java.util.concurrent.atomic.AtomicLong + /** * ÇøÓò±ê×¼»¯ * 1.Ð¡Çø¿âÏçÕò½ÖµÀ±ê×¼»¯£¬°üº¬Ð¡Çø£¬ÉÌÆÌ£¬Ð´×ÖÂ¥ @@ -22,6 +36,7 @@ class TownStandardBatch extends BaseBatch{ def fullCityMap = CommonDatautils.queryFullNameCity() def regionMap = com.fangjia.script.commData.CommonDatautils.queryAllRegionNameByCity() def regionFullNameMap = com.fangjia.script.commData.CommonDatautils.queryAllRegionFullNameByCity() + public static ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10) def updateList = [] def addAliasList = [] @@ -38,7 +53,9 @@ class TownStandardBatch extends BaseBatch{ def TownStandard(){ // townStandardByCat("office") - townStandardByPoi() +// townStandardByPoi() + addTownByTownShape()//ΪûÓÐÏçÕò½ÖµÀµÄpoi£¬²¹³äÏçÕò½ÖµÀ£¬ºöÂÔÇøÓò£¬²¢Ê¹ÓõØÍ¼ +// updateTownData() } def townStandardByCat(def cat){ //"ÈýÃ÷","ÁúÑÒ","ÄÏÆ½","ÕÄÖÝ","¸£ÖÝ","ÏÃÃÅ","ȪÖÝ","ÆÎÌï","ÄþµÂ", @@ -69,11 +86,15 @@ class TownStandardBatch extends BaseBatch{ updateList << ["Êý¾ÝID", "³ÇÊÐ","ÇøÓò","ÏçÕò½ÖµÀ","Ãû³Æ","״̬", "ÐÞ¸Ä"] addAliasList << ["³ÇÊÐ","ÇøÓò","ÏçÕò½ÖµÀ", "ÐÂÔö±ðÃû"] - //Õã½­£¬½­ËÕ£¬°²»Õ - def citys = ['º¼ÖÝ','Äþ²¨','ÎÂÖÝ','¼ÎÐË','̨ÖÝ','ºþÖÝ','ÉÜÐË','½ð»ª','ÖÛɽ','áéÖÝ','ÀöË®']//CommonDatautils.findAllCity() + def runProvinces = ["¸£½¨Ê¡","Õã½­Ê¡","½­ËÕÊ¡","°²»ÕÊ¡","ɽ¶«Ê¡","¸ÊËàÊ¡"] + def citys = CommonDatautils.findAllCity() + def index = 0 for(def city : citys){ - + index++ def data = fullCityMap.get(city) +// if(runProvinces.contains(data.province)){ +// continue +// } def fullCityName = null if(data){ fullCityName = data.city @@ -95,11 +116,16 @@ class TownStandardBatch extends BaseBatch{ def rets = readPoiCsv(fileName) println city +" "+rets.size() if(set.size()>1){ - poiHaveRegionProcess(fullCityName, townMap, rets, mzbRegionMap) + poiHaveRegionProcess(fullCityName, townMap, rets, mzbRegionMap, data) }else{ // haveStreetProcess(city, set, cat) } } + if(updateList.size()>50000){ + ExcelUtils.write("D:\\Êý¾Ý\\ÏçÕò½ÖµÀ´ý²éÊý¾Ý-${index}.xlsx", updateList, "Êý¾Ý") + ExcelUtils.write("D:\\Êý¾Ý\\ÏçÕò½ÖµÀ´ý²éÊý¾Ý-ÐèÐÂÔö±ðÃû-${index}.xlsx", addAliasList, "Êý¾Ý") + updateList.clear() + } }else{ println fileName+" ÎļþûÕÒµ½" } @@ -107,8 +133,7 @@ class TownStandardBatch extends BaseBatch{ println "ûÕÒµ½ÏàÓ¦µÄÈ«³Æ£º"+city } } - ExcelUtils.write("D:\\Êý¾Ý\\ÏçÕò½ÖµÀ´ý²éÊý¾Ý.xlsx", updateList, "Êý¾Ý") - ExcelUtils.write("D:\\Êý¾Ý\\ÏçÕò½ÖµÀ´ý²éÊý¾Ý-ÐèÐÂÔö±ðÃû.xlsx", addAliasList, "Êý¾Ý") + ExcelUtils.write("D:\\Êý¾Ý\\ÏçÕò½ÖµÀ´ý²éÊý¾Ý-×îºó.xlsx", updateList, "Êý¾Ý") } def haveRegionProcess(city, fullCityName, townMap, cat, shortRegionNameMap){ @@ -168,7 +193,7 @@ class TownStandardBatch extends BaseBatch{ } - def poiHaveRegionProcess(fullCityName, townMap, rets, mzbRegionMap){ + def poiHaveRegionProcess(fullCityName, townMap, rets, mzbRegionMap, data){ def results = [] if(fullCityName){ for(def d : rets){ @@ -221,21 +246,21 @@ class TownStandardBatch extends BaseBatch{ def m = [:] m.put(d.id, ["township":updateTown]) results << m -// if(results.size()%100==0){ -// updateByEs(results) -// results.clear() -// } - updateList << [d.id, d.city, d.district, d.name,d.township, d.status, updateTown] + if(results.size()%100==0){ + updateByEs(results) + results.clear() + } + updateList << [d.id, d.province, d.city, d.district, d.name,d.township, d.status, updateTown] // println d.city +" "+d.district+" "+d.name +" "+d.township+" ÏçÕòÐÞ¸ÄΪ£º"+updateTown }else{ def m = [:] m.put(d.id, ["township":""]) -// results << m -// if(results.size()%100==0){ -// updateByEs(results) -// results.clear() -// } - updateList << [d.id, d.city, d.district, d.name, d.township, d.status, ""] + results << m + if(results.size()%100==0){ + updateByEs(results) + results.clear() + } + updateList << [d.id, d.province, d.city, d.district, d.name, d.township, d.status, ""] println d.city +" "+d.district+" "+d.name +" "+d.township+" ״̬ÐÞ¸ÄΪ£º¿ÕÖµ" } } @@ -244,10 +269,10 @@ class TownStandardBatch extends BaseBatch{ } } -// if(results.size()>0){ -// updateByEs(results) -// results.clear() -// } + if(results.size()>0){ + updateByEs(results) + results.clear() + } println fullCityName +" ´¦ÀíÍê³É" } @@ -322,18 +347,334 @@ class TownStandardBatch extends BaseBatch{ if(line){ String[] arrs = line.split("\\|@\\|") def o = new BasicDBObject() - o.put("city", arrs[0]) - o.put("district", arrs[1]) - o.put("name", arrs[2]) - o.put("township", arrs[3]) - o.put("status", arrs[4]) - o.put("id", arrs[5]) - rets << o + try{ + o.put("city", arrs[0]) + o.put("district", arrs[1]) + o.put("name", arrs[2]) + o.put("township", arrs[3]) + o.put("status", arrs[4]) + o.put("id", arrs[5]) + rets << o + }catch(Exception e){ + println arrs + } + } } return rets; } + def readCSV2(filename){ + def lines = FileUtils.readLines(new File(filename)) + def rets = []; + def index = 0 + for(line in lines) { + if(line && index>=1){ + String[] arrs = line.split(",") + def o = new BasicDBObject() + try{ + o.put("id", arrs[1]) + o.put("province", arrs[2]) + o.put("city", arrs[3]) + o.put("district", arrs[4]) + o.put("lng", arrs[5]) + o.put("lat", arrs[6]) + if(arrs.size()<=7){ + o.put("data_source","") + }else{ + o.put("data_source", arrs[7]) + } + rets << o + }catch(Exception e){ + println arrs + } + } + index++ + } + return rets; + } + + def readCSV3(filename){ + def lines = FileUtils.readLines(new File(filename)) + def rets = []; + def index = 0 + for(line in lines) { + if(line && index>=1){ + String[] arrs = line.split(",") + if(arrs.size()>=10 && arrs[7] && arrs[9]=="Í¬ÇøÓò"){ + def o = new BasicDBObject() + try{ + o.put("id", arrs[0]) + o.put("township", arrs[7]) + if(arrs.size()>=9 && arrs[8]){ + o.put("district", arrs[8]) + } + if(arrs.size()>=10 && arrs[9]){ + o.put("way", arrs[9]) + } + rets << o + }catch(Exception e){ + println arrs + } + } + + } + index++ + } + return rets; + } + + def addTownByTownShape(){ + def i = 0 + def headers = ["_id","province","city","district","lng","lat","data_source","ÏçÕò½ÖµÀ", "ÐÂÇøÓò", "·½Ê½", "±ê×¼ÏçÕò"] + while(i<50){ + def fileName = "/home/goojia/gj/new_poi/input/map/no_township_${i}.csv" + if (CommonDatautils.isWindow()) { + fileName = "D:\\Êý¾Ý\\Êý¾Ý½¨Éè\\ÏçÕò½ÖµÀ\\´ý²¹³äÏçÕò½ÖµÀ\\ԭʼ\\no_township_${i}.csv" + } + File file=new File(fileName); + if(file.exists()) { + def rets = readCSV2(fileName) + println i +" "+ rets.size() + def rows = addTownshipBatch(rets) + if (CommonDatautils.isWindow()) { + com.fangjia.script.gj.ccb.FileUtils.batchCreateFileByCustomSuffix(rows, "D:\\Êý¾Ý\\Êý¾Ý½¨Éè\\ÏçÕò½ÖµÀ\\´ý²¹³äÏçÕò½ÖµÀ\\½á¹û-µØÍ¼\\no_township_result_${i}.csv", headers, "utf-8", false, ',', ''); + }else{ + com.fangjia.script.gj.ccb.FileUtils.batchCreateFileByCustomSuffix(rows, "/home/goojia/gj/new_poi/output/no_township_result_${i}.csv", headers, "utf-8", false, ',', ''); + } + println fileName +" ÔËÐÐÍê³É" + }else{ + println fileName +" ²»´æÔÚ" + } + i++ + } + } + + def addTownshipBatch(def rets){ + def results = new CopyOnWriteArrayList() + def totalCount = new AtomicLong() + final CountDownLatch latch = new CountDownLatch(rets.size()) + for(def i=0;i= 1) { + addTown(r, townMap, ["lon":r.lng.toString().toDouble(), "lat":r.lat.toString().toDouble()]) + results << [r.id, r.province, r.city, r.district, r.lng, r.lat, r.data_source, r.township, r.new_district, r.town_source, r.strand_town] +// } + } + } catch (Exception e) { + e.printStackTrace() + } finally { + latch.countDown() + } + } + }); + } + latch.await() + return results + } + + def addTown(saveObj, townMap, location) { + //ÔÚpoi±¾ÇøÓòÏÂͨ¹ýÏçÕò½ÖµÀΧÀ¸Ñ¡³öËùÔÚÏçÕò½ÖµÀ +// def towns = townMap.get(saveObj.district) +// if (towns) { +// for (def town : towns) { +// if (town.shape && town.shape.coordinates) { +// def flag = InsidePolygon.isInArea(location.lon, location.lat, InsidePolygon.createPoint4(town.shape.coordinates)) +// if (flag) { +// saveObj.township = town.street +// saveObj.town_source = "Í¬ÇøÓò" +// saveObj.strand_town = "ÊÇ" +// break +// } +// } +// } +// } + //ºöÂÔpoiÖеÄÇøÓò ͨ¹ýÏçÕò½ÖµÀΧÀ¸Ñ¡³öËùÔÚÏçÕò½ÖµÀ +// if(!saveObj.township){ +// def townNames = townMap.keySet() +// for(def townName : townNames){ +// towns = townMap.get(townName) +// for (def town : towns) { +// if (town.shape && town.shape.coordinates) { +// def flag = InsidePolygon.isInArea(location.lon, location.lat, InsidePolygon.createPoint4(town.shape.coordinates)) +// if (flag) { +// saveObj.township = town.street +// saveObj.new_district = town.mzb_district_name +// saveObj.town_source = "ºöÂÔÇøÓò" +// saveObj.strand_town = isStandTown(townMap, saveObj.new_district, saveObj.township) +// break +// } +// } +// } +// if(saveObj.township){ +// break; +// } +// } +// } + //ͨ¹ýµ÷È¡µØÍ¼api½Ó¿Ú»ñÈ¡ÏçÕò½ÖµÀ + if(!saveObj.township){ + def gaodeMap = getTownshipInfo(location.lon+","+location.lat) + if(gaodeMap && gaodeMap.township){ + saveObj.township = gaodeMap.township + saveObj.new_district = gaodeMap.district + saveObj.town_source = "¸ßµÂAPI" + saveObj.strand_town = "" +// if(townMap.size()>=1){ +// saveObj.strand_town = isStandTown(townMap, saveObj.new_district, saveObj.township) +// } + } + } + +// //ͨ¹ýµ÷È¡µØÍ¼api½Ó¿Ú»ñÈ¡ÏçÕò½ÖµÀ +// if(!saveObj.township){ +// def gaodeMap = BaiduMapUtils.geocoding(location.lat+","+location.lon) +// if(gaodeMap && gaodeMap.addressComponent) { +// def addressComponent = gaodeMap.addressComponent +// if(addressComponent){ +// if(addressComponent.town){ +// saveObj.township = addressComponent.town +// saveObj.new_district = addressComponent.district +// saveObj.town_source = "°Ù¶ÈAPI" +// saveObj.strand_town = isStandTown(townMap, saveObj.new_district, saveObj.township) +// } +// } +// } +// } + return saveObj + } + + def isStandTown(townMap, district, town){ + def towns = townMap.get(district) + def flag = "·Ç" + if(towns){ + for(def t : towns){ + if(t.street == town){ + flag = "ÊÇ" + break + } + } + } + return flag + } + + + def getTownshipInfo(def glocation){ + def township = null + def district = null + def city = null + def format_addr = null + def stop = false + def count = 0 + def jsonObject = null +// while(!stop){ + if(glocation){ + jsonObject = GaoDeApiUtils.geocode(glocation) + + if(jsonObject && jsonObject.regeocode) { + def addressComponent = jsonObject.regeocode.addressComponent + if(addressComponent){ + township = addressComponent.township + district = addressComponent.district + city = addressComponent.city + format_addr = jsonObject.regeocode.formatted_address + + } + } + } +// if(jsonObject.status==0 || count>3){ +// stop = true +// println "¸ßµÂµ÷Óó¬3´Î" +// }else{ +// count ++ +// Thread.sleep(3000) +// print "." +// } +// } + + def map = [:] + map.city = city + map.district = district + map.township = township + map.format_addr = format_addr + return map; + } + + def updateTownData(){ + def i = 0 + while(i<50) { + def fileName = "/home/goojia/gj/new_poi/output/no_township_result_${i}.csv" + if (CommonDatautils.isWindow()) { + fileName = "D:\\Êý¾Ý\\Êý¾Ý½¨Éè\\ÏçÕò½ÖµÀ\\´ý²¹³äÏçÕò½ÖµÀ\\½á¹û\\no_township_result_${i}.csv" + } + File file = new File(fileName); + if (file.exists()) { + def rets = readCSV3(fileName) + println file.getAbsoluteFile().getName() +" "+(rets.size()*100/200000)+"%"+" "+rets.size() +// if(rets){ +// updateToEs(rets) +// } + + } + i++ + } + } + + + def updateToEs(rows){ + BulkRequest request = new BulkRequest(); + int batchSize = 1; + int processedCount = 0; + def client = ElasticUtils.getClient89("192.168.0.89") + for (int i = 0; i < rows.size(); i++) { + def map = rows[i] + if(map.containsKey("way")){ + map.remove("way") + } + request.add(new IndexRequest("map_poi_2024", "_doc", map.id).source(map, XContentType.JSON)); + if(i%1000==0){ + print "." + } + + // ÅúÁ¿Ìá½»Êý¾Ý + if (request.numberOfActions() >= batchSize) { + request.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); + BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT); + if (bulkResponse.hasFailures()) { + // ´¦Àí´íÎó + print "Bulk request has failures: " + bulkResponse.buildFailureMessage() + } else { + processedCount += request.numberOfActions(); + println "Processed " + processedCount + " documents" + } + + request = new BulkRequest(); + } + + } + + if (request.numberOfActions() > 0) { + request.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); + BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT); + if (bulkResponse.hasFailures()) { + // ´¦Àí´íÎó + println "Bulk request has failures: " + bulkResponse.buildFailureMessage() + } else { + processedCount += request.numberOfActions(); + println "Processed " + processedCount + " documents" + } + } + + println "½áÊøÊ±¼ä "+new Date() + } } diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/TownshipStrandUpdate.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/TownshipStrandUpdate.groovy index d99e249c9..bbe074507 100644 --- a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/TownshipStrandUpdate.groovy +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/data_handle/TownshipStrandUpdate.groovy @@ -38,16 +38,16 @@ class TownshipStrandUpdate { static main(args) { def task = new TownshipStrandUpdate() -// task.process() -// task.updateTown() + task.process() + task.updateTown() // task.stat() - task.updateDiffRegionTown() +// task.updateDiffRegionTown() // task.cleanTown() // task.checkTownFromMongo() // task.updateTownMapping() // task.updateDevMapping() - println new Date().getTime() +// println new Date().getTime() // task.updateSpecCityTown() } diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/district/DistrictFieldAddBatch.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/district/DistrictFieldAddBatch.groovy index 3b3aed61a..8507f7d00 100644 --- a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/district/DistrictFieldAddBatch.groovy +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/district/DistrictFieldAddBatch.groovy @@ -18,6 +18,8 @@ import com.mongodb.BasicDBObject import com.mongodb.DBCollection import com.rabbitmq.client.impl.AMQImpl import org.bson.types.ObjectId +import org.elasticsearch.index.query.QueryBuilder +import org.elasticsearch.index.query.QueryBuilders import java.text.SimpleDateFormat import java.util.concurrent.CopyOnWriteArrayList @@ -39,7 +41,7 @@ class DistrictFieldAddBatch extends BaseBatch{ //"°²¾Ó¿Í":"°²¾Ó¿ÍС³ÌÐò","Á´¼Ò":"Á´¼Ò","ÐÒ¸£Àï":"ÐÒ¸£Àï","³ÇÊз¿²ú":"³ÇÊз¿²úС³ÌÐò","ËÑ·¿":"ËÑ·¿" // - def sourceMap = ["ÐÒ¸£Àï":"ÐÒ¸£ÀïAPP","³ÇÊз¿²ú":"³ÇÊз¿²úС³ÌÐò","°²¾Ó¿ÍС³ÌÐò":"°²¾Ó¿ÍС³ÌÐò","°²¾Ó¿ÍÒÆ¶¯¶Ë":"°²¾Ó¿ÍÒÆ¶¯¶Ë","±´¿ÇÕÒ·¿":"±´¿ÇÕÒ·¿","°²¾Ó¿Í-з¿":"°²¾Ó¿Í-з¿","°²¾Ó¿Í":"°²¾Ó¿Í","Á´¼Ò":"Á´¼Ò","±´¿ÇÕÒ·¿-з¿":"±´¿ÇÕÒ·¿-з¿","Â¥ÅÌÍø-з¿":"Â¥ÅÌÍø-з¿","ìûÌ©":"Öйú·¿¼ÛÐÐÇé","Á´¼Ò":"Á´¼Ò","ËÑ·¿":"ËÑ·¿","ÎÒ°®ÎÒ¼Ò":"ÎÒ°®ÎÒ¼Ò","Öî¸ðÕÒ·¿":"Öî¸ðÕÒ·¿APP","±´¿ÇÕÒ·¿":"±´¿ÇÕÒ·¿", + def sourceMap = ["±´¿ÇÕÒ·¿":"±´¿ÇÕÒ·¿","Á´¼Ò":"Á´¼Ò","±´¿ÇÕÒ·¿-з¿":"±´¿ÇÕÒ·¿-з¿","°²¾Ó¿Í":"°²¾Ó¿Í","ÐÒ¸£Àï":"ÐÒ¸£Àï","°²¾Ó¿ÍС³ÌÐò":"°²¾Ó¿ÍС³ÌÐò","³ÇÊз¿²ú":"³ÇÊз¿²úС³ÌÐò","°²¾Ó¿ÍÒÆ¶¯¶Ë":"°²¾Ó¿ÍÒÆ¶¯¶Ë","°²¾Ó¿Í-з¿":"°²¾Ó¿Í-з¿","Â¥ÅÌÍø-з¿":"Â¥ÅÌÍø-з¿","ìûÌ©":"Öйú·¿¼ÛÐÐÇé", "³ÇÊз¿²ú":"³ÇÊз¿²ú","ËÑ·¿":"ËÑ·¿","ÎÒ°®ÎÒ¼Ò":"ÎÒ°®ÎÒ¼Ò","Öî¸ðÕÒ·¿":"Öî¸ðÕÒ·¿", "ÀÖÓмÒ":"ÀÖÓмÒ","¼ªÎÝ":"¼ªÎÝ","C21":"C21","365ÌÔ·¿":"365ÌÔ·¿"] //key:ÄÂÈںϱíµÄÀ´Ô´ valve:es½âÎö±íµÄÀ´Ô´ @@ -61,6 +63,7 @@ class DistrictFieldAddBatch extends BaseBatch{ "car_site_count":"³µÎ»","car_site":"³µÎ»ÃèÊö","property_life":"²úȨÄêÏÞ","address":"µØÖ·","build_structure":"½¨Öþ½á¹¹", "build_type":"½¨ÖþÀàÐÍ", "land_property":"ȨÊôÀà±ð","live_date":"Èëסʱ¼ä","loop_line_info":"»·Ïß"] + final DBCollection thirdSeaweedMappingColl = MongoUtils.getCollectionByName("fangjia_craw", "third_seaweed_mapping", "192.168.0.235", 27018) final static def EMAILS = [ "gaojuan@fangjia.com" @@ -68,6 +71,38 @@ class DistrictFieldAddBatch extends BaseBatch{ static main(args) { runBatch(new DistrictFieldAddBatch(), args) +// ExcelUtils.multiThreadingModify("D:\\Êý¾Ý\\Ð¡Çø\\ÉϺ£±ðÊû.xlsx",{d-> +// def dist = CommonDatautils.findDistrict(d['B'], d['G'], d['C'], "district") +//// if(dist){ +//// d['L'] = dist.loudong_count +//// d['M'] = dist.household_count +//// d['Q'] = dist.estate_type2 +//// } +// def list = findEsDatasByCityAndName(d['B'], d['G'], d['C'], "ËÑ·¿") +// if(!list && dist){ +// def alias = dist.alias +// for(def name : alias){ +// list = findEsDatasByCityAndName(d['B'], d['G'], name, "ËÑ·¿") +// if(list){ +// d['Z'] = "±ðÃû" +// } +// } +// }else{ +// d['Z'] = "Ãû³Æ" +// } +// if(list){ +// def obj = list[0] +// if(obj.loudong_cnt){ +// d['W'] = obj.loudong_cnt +// } +// +// if(obj.households){ +// d['X'] = obj.households +// } +// d['Y'] = obj.url +// } +// +// }) } @Override @@ -83,18 +118,13 @@ class DistrictFieldAddBatch extends BaseBatch{ headers << fieldsNameMap.get(it) } - headers << "ץȡÁ¿" - headers << "Æ¥ÅäÁ¿" - headers << "0.9·ÖÒÔÉÏÁ¿" - headers << "Æ¥ÅäÂÊ" - headers << "0.9ÒÔÉÏÆ¥ÅäÂÊ" -// analysRets << headers - for(def c : citys){ + def totalCount = CommonDatautils.findAllDistrictCount("district", c) if(totalCount){ // rh_analysRets = addFieldFromRonghe(c, totalCount, rh_analysRets)//ÈÚºÏ - analysRets = addFieldFromMatch(c, totalCount, analysRets)//Æ¥Åä +// analysRets = addFieldFromMatch(c, totalCount, analysRets)//Æ¥Åä + analysRets = addFieldFromMatchMapping(c, totalCount, analysRets)//ÐÂ¾ÉÆ¥ÅäÖмä±í } } println analysRets.toString() @@ -107,8 +137,10 @@ class DistrictFieldAddBatch extends BaseBatch{ sourceMap.each { seaweedmapSource, esWebSource -> def esRets = findEsDatas(c, esWebSource) + def matchRets1 = matchApi(esRets) def matchRets2 = selectRestByCredit(matchRets1) + println esWebSource +" ץȡÁ¿£º"+esRets.size()+" Æ¥ÅäÁ¿£º"+matchRets1.size()+" 0.9·ÖÒÔÉÏÁ¿£º"+matchRets2.size() def updateRets = processFieldsFromMatch(c , matchRets2, esWebSource) @@ -140,6 +172,65 @@ class DistrictFieldAddBatch extends BaseBatch{ } + def addFieldFromMatchMapping(c, totalCount, analysRets){ + def fields = fieldsMap.keySet() as List + + sourceMap.each { seaweedmapSource, esWebSource -> + def esRets = findMatchSameDatas(c, esWebSource) + println esWebSource +" ÐÂÀÏË㷨ƥÅäÏàͬÁ¿£º"+esRets.size() + + def updateRets = processFieldsFromMatch(c , esRets, esWebSource) + + def precentMap = fieldUpdate(totalCount, updateRets) + println c +" "+precentMap.toString() + updateDB(c, updateRets) + println "------------------------------------------------------------------------------" + + def analyRet = [] + analyRet << seaweedmapSource + analyRet << c + fields.each{key-> + analyRet << precentMap.get(key) + } + analyRet << esRets.size() + analysRets << analyRet + } + return analysRets; + + } + + + def findMatchSameDatas(c, esWebSource){ + def query = new BasicDBObject("city", c).append("source", esWebSource).append("match_id", new BasicDBObject('$exists', true)).append("old_match_id", new BasicDBObject('$exists',true)) + def siteDatas = thirdSeaweedMappingColl.find(query).toList() + def rows = new CopyOnWriteArrayList() + def totalCount = new AtomicLong() + final CountDownLatch latch = new CountDownLatch(siteDatas.size()) + for(def i=0;i + list << r + }) + return list + } + def fieldUpdate(total,updateRets){ def countMap = [:] @@ -621,4 +722,26 @@ class DistrictFieldAddBatch extends BaseBatch{ jms.sendMail(email, "×Ö¶ÎÌî³äÇé¿ö·ÖÎö", sb.toString()+rh_sb.toString()); } } + + def findCommunities(url){ + if(!url){ + return null + } + QueryBuilder queryBuilder = QueryBuilders.boolQuery().must(QueryBuilders.termQuery("url", url)) + def rets = [] + def datas = null + try{ + datas = ElasticUtils.executeSimpleQuery("192.168.0.206", "community", queryBuilder); + }catch(Exception e){ + findCommunities(url) + } + def obj = null + if(datas) { + for (int k = 0; k < datas.size(); k++) { + def d = datas[k]; + obj = d + } + } + return obj; + } } diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/district/DistrictStatRentCleanBatch.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/district/DistrictStatRentCleanBatch.groovy new file mode 100644 index 000000000..edb26ccb1 --- /dev/null +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/district/DistrictStatRentCleanBatch.groovy @@ -0,0 +1,54 @@ +package com.fangjia.script.gj.district + +import com.fangjia.script.BaseBatch +import com.fangjia.script.BatchOwner +import com.fangjia.script.Watcher +import com.fangjia.script.commData.CommonDatautils +import com.fangjia.script.util.MongoUtils +import com.mongodb.BasicDBObject +import com.mongodb.DBCollection + +@BatchOwner(Watcher.GaoJuan) +class DistrictStatRentCleanBatch extends BaseBatch{ + + public static final def mongoDbUrl = "mongodb://developer:G00IDCDEV12385@mongo.db.fangjia.com:28017"; + public static final DBCollection RENT_DIST_STAT_COLL = MongoUtils.getCollectionByName2("fangjia", "district_stat_rent", mongoDbUrl) + + static main(args) { + runBatch(new DistrictStatRentCleanBatch(), args) + } + + @Override + void process(Object args) { + def citys = CommonDatautils.findAllCity() + for(def c : citys){ + def keys = CommonDatautils.getSimpleDistricts("district", c) + running(keys, c) + println c +" ÔËÐÐÍê³É" + } + } + + def running(keys, c){ + def q = new BasicDBObject("city", c).append("district_name", new BasicDBObject('$ne','')) + def fields = new BasicDBObject() + fields.put("city", 1) + fields.put("region", 1) + fields.put("district_name", 1) + def dbcursor = RENT_DIST_STAT_COLL.find(q, fields).batchSize(10000) + def delRets = [] + for(def d : dbcursor){ + if(d.district_name && !keys.contains(d.city+"@"+d.region+"@"+d.district_name)){ + println d.city+"@"+d.region+"@"+d.district_name + delRets << d._id + } + if(delRets.size()>=100){ + def delquery = new BasicDBObject() + delquery.put("_id", new BasicDBObject('$in', delRets)) + RENT_DIST_STAT_COLL.remove(delquery) + delRets.clear() + } + } + } + + +} diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/district/FangjiaClientUtils.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/district/FangjiaClientUtils.groovy index 15e4cc80b..35179b3d9 100644 --- a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/district/FangjiaClientUtils.groovy +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/district/FangjiaClientUtils.groovy @@ -398,4 +398,32 @@ class FangjiaClientUtils { return jsonObj; } + + /** + * ¾­Î³¶Èת»» + * 1¡¢¸ßµÂת°Ù¶È 2¡¢¸ßµÂתWGS84 3¡¢°Ù¶Èת¸ßµÂ 4¡¢WGS84ת¸ßµÂ 5¡¢°Ù¶ÈתWGS84 6¡¢WGS84ת°Ù¶È + */ + public static def convert(String locationstr, type){ + def jsonObj = null + def content = null + def points = [] + try { + def url = "http://192.168.0.19:31080/FangJiaNlpService/convert?locations="+URLEncoder.encode(locationstr,"UTF-8")+"&coordsys=${type}" + + content = new HttpRequest().newGet(url, null, "utf-8") + jsonObj = JSONObject.fromObject(content) + if(jsonObj && jsonObj.locations){ + def locations = jsonObj.locations + for(def s : locations){ + def arrs = s.split(",") + points = [arrs[0].toString().toDouble(), arrs[1].toString().toDouble()] + } + } + return points + } catch (Exception e) { + println e.getMessage() + } + return null; + } + } diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/district/UpdateDistrictField.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/district/UpdateDistrictField.groovy new file mode 100644 index 000000000..f44d8bf4b --- /dev/null +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/district/UpdateDistrictField.groovy @@ -0,0 +1,414 @@ +package com.fangjia.script.gj.district + +import com.fangjia.script.BaseBatch +import com.fangjia.script.BatchOwner +import com.fangjia.script.Watcher +import com.fangjia.script.commData.CommonDatautils +import com.fangjia.script.gj.FiledStrand +import com.fangjia.script.util.DbUtils +import com.fangjia.script.util.ElasticUtils +import com.fangjia.script.util.MongoUtils +import com.mongodb.BasicDBObject +import com.mongodb.DBCollection +import org.bson.types.ObjectId +import org.elasticsearch.index.query.QueryBuilder +import org.elasticsearch.index.query.QueryBuilders + +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.CountDownLatch +import java.util.concurrent.ExecutorService +import java.util.concurrent.Executors +import java.util.concurrent.atomic.AtomicLong + +/** + * ¸ù¾ÝÁ´¼ÒÊý¾ÝÐÞ¸ÄÐ¡Çø¿âÖÐ×Ö¶Î + * ʹÓõ½ÖмäÓ³Éä±í + */ +@BatchOwner(Watcher.GaoJuan) +class UpdateDistrictField extends BaseBatch{ + + final DBCollection thirdSeaweedMappingColl = MongoUtils.getCollectionByName("fangjia_craw", "third_seaweed_mapping", "192.168.0.235", 27018) + public static ExecutorService fixedThreadPool = Executors.newFixedThreadPool(20) + + def fields = ["developer","estate_company","household_count","loudong_count","estate_charge","car_site_count"] + + def sources = ["Á´¼Ò", "ÎÒ°®ÎÒ¼Ò", "°²¾Ó¿Í"] + + def statMap = [:] + + static main(args) { + runBatch(new UpdateDistrictField(), args) + } + + @Override + void process(Object args) { + def sourceMap = [:] + sources.each {source-> + def valMap = findThirdMatchDist(source) + println source +" "+valMap.size() + if(valMap){ + sourceMap.put(source, valMap) + } + } + def margeResults = megerDatas(sourceMap) + updateDB(margeResults) + println "ÐÞ¸ÄÍê³É "+new Date().toString() + } + + def megerDatas(sourceMap){ + def set = new HashSet() + sources.each {source-> + def valMap = sourceMap.get(source) + set.addAll(valMap.keySet()) + } + def lastValues = [] + set.each {id-> + + def dbObj = CommonDatautils.findDistrictById(id) + + def datas = [] + sources.each {source-> + def valMap = sourceMap.get(source) + def sourceEsObj = findCommunities(valMap.get(id)) + if(sourceEsObj){ + if(source == "Á´¼Ò"){ + sourceEsObj.source = "lianjia" + }else if(source == "ÎÒ°®ÎÒ¼Ò"){ + sourceEsObj.source = "wiwj" + }else if(source == "°²¾Ó¿Í"){ + sourceEsObj.source = "anjuke" + } + datas << sourceEsObj + } + } + if(dbObj && datas){ + def newValMap = getNewField2(datas, dbObj) + if(newValMap){ + newValMap.put("id", id) + lastValues << newValMap + } + } + } + + statMap.each {source,fieldMap-> + println source +" "+fieldMap.size() + fieldMap.each{f,v-> + println f+" "+ v + } + println "----------------------------------------" + } + return lastValues + } + + +// def margeValue(lianjiaMap, wiwjMap, anjukeMap){ +// def lianjisIds = lianjiaMap.keySet() +// def wiwjIds = wiwjMap.keySet() +// def anjukeIds = anjukeMap.keySet() +// def set = new HashSet() +// set.addAll(lianjisIds) +// set.addAll(wiwjIds) +// set.addAll(anjukeIds) +// +// def lastValues = [] +// def lianjiaUpdateCount = 0 +// def wiwjUpdateCount = 0 +// def anjukeUpdateCount = 0 +// def lianjiaCountMap = [:] +// def wiwjCountMap = [:] +// def anjukeCountMap = [:] +// set.each {id-> +// BasicDBObject newValMap = new BasicDBObject() +// fields.each {field-> +// def lianjiaValMap = lianjiaMap.get(id) +// def wiwjValMap = wiwjMap.get(id) +// def anjukeValMap = anjukeMap.get(id) +// if(lianjiaValMap && lianjiaValMap.containsKey(field)){ +// newValMap.put(field, lianjiaValMap.get(field)) +// lianjiaUpdateCount++ +// def count = lianjiaCountMap.get(field) +// if(!count){ +// lianjiaCountMap.put(field, 1) +// }else{ +// lianjiaCountMap.put(field, count + 1) +// } +// }else if(wiwjValMap && wiwjValMap.containsKey(field)){ +// newValMap.put(field, wiwjValMap.get(field)) +// wiwjUpdateCount++ +// def count = wiwjCountMap.get(field) +// if(!count){ +// wiwjCountMap.put(field, 1) +// }else{ +// wiwjCountMap.put(field, count + 1) +// } +// }else if(anjukeValMap && anjukeValMap.containsKey(field)){ +// newValMap.put(field, anjukeValMap.get(field)) +// anjukeUpdateCount++ +// def count = anjukeCountMap.get(field) +// if(!count){ +// anjukeCountMap.put(field, 1) +// }else{ +// anjukeCountMap.put(field, count + 1) +// } +// } +// } +// newValMap.put("id", id) +// lastValues << newValMap +// } +// +// lianjiaCountMap.each {k,v-> +// println "[Á´¼Ò] "+k+" "+v +// } +// +// wiwjCountMap.each {k,v-> +// println "[ÎÒ°®ÎÒ¼Ò] "+k+" "+v +// } +// +// anjukeCountMap.each {k,v-> +// println "[°²¾Ó¿Í] "+k+" "+v +// } +// return lastValues +// } + + def updateDB(margeResults){ + for(def mr : margeResults){ + def id = mr.get("id") + mr.remove("id") + mr.put("m_date", new Date()) + DbUtils.seaweed.update(new BasicDBObject('_id',new ObjectId(id)),new BasicDBObject('$set',mr)) + } + } + +// def batchUpdateDist(source){ +//// def rets = findThirdMatchDist(source) +// println "[${source}] ·û±£Ìõ¼þÐ¡ÇøÁ¿£º"+rets.size() +// def updateIndex = new AtomicLong() +// final CountDownLatch latch = new CountDownLatch(rets.size()) +// def allUpdateList = new CopyOnWriteArrayList() +// +// def sourceMap = new ConcurrentHashMap() +// +// for(def i=0;i +// def count = countMap.get(k) +// if(!count){ +// countMap.put(k, 1) +// }else{ +// countMap.put(k, count+1) +// } +// } +// } +// +// countMap.each {k,v-> +// println k +" ¸üÐÂÁ¿£º"+v +// } +// +// println "---------------------------------------------------------" +// return sourceMap +// } + + def running(url, old_match_id){ + def esObj = findCommunities(url) + def dbObj = CommonDatautils.findDistrictById(old_match_id) + if(dbObj){ + def newValMap = getNewField(esObj, dbObj) + return newValMap + } + return null + } + + def getNewField(esObj, dbObj){ + BasicDBObject newValMap = new BasicDBObject() + esObj.each{field, esVal-> + def dbVal = dbObj.get(field) + def newVal = null + if(esVal && field=="developer" && esVal!=dbVal){ + newVal = FiledStrand.processCompany(esVal) + + } + if(esVal && field=="estate_company" && esVal!=dbVal){ + newVal = FiledStrand.processCompany(esVal) + } + + if(esVal && field=="household_count" && esVal!=dbVal){ + newVal = FiledStrand.processHouseholdCount(esVal, dbObj.estate_type2) + } + + if(esVal && field=="loudong_count" && esVal!=dbVal){ + newVal = FiledStrand.processLoudongCount(esVal) + } + + if(esVal && field=="estate_charge" && esVal!=dbVal){ + def numVal = FiledStrand.getNumber(esVal) + if(numVal && numVal.toString().toDouble()!=dbVal){ + newVal = FiledStrand.processEstateCharge(dbObj.city, numVal, dbObj.estate_type2) + newVal = newVal.toString() + } + } + if(esVal && field=="car_site_count"){ + def numVal = FiledStrand.getNumber(esVal) + if(numVal && numVal.toString().toInteger()!=dbVal){ + newVal = FiledStrand.processCarSite(numVal) + } + } + if(newVal){ + newValMap.put(field, newVal) + } + + } + + return newValMap + } + + def getNewField2(esDatas, dbObj){ + BasicDBObject newValMap = new BasicDBObject() + def lastValueMap = [:] + def haveValueMap = [:] + fields.each{field-> + for(def esData : esDatas){ + def esVal = esData.get(field) + def dbVal = dbObj.get(field) + def newVal = null + if(haveValueMap.containsKey(field)){ + continue + }else{ + if(lastValueMap.containsKey(field)){ + continue + } + if(esVal){ + + if(field=="estate_charge" || field=="car_site_count") { + esVal = FiledStrand.getNumber(esVal) + } + if(dbVal && esVal.toString()==dbVal.toString()){ + haveValueMap.put(field, esVal) + }else{ + if(field=="developer" && esVal!=dbVal){ + newVal = FiledStrand.processCompany(esVal) + } + + if(field=="estate_company" && esVal!=dbVal){ + newVal = FiledStrand.processCompany(esVal) + } + + if(field=="household_count" && esVal!=dbVal){ + newVal = FiledStrand.processHouseholdCount(esVal, dbObj.estate_type2) + } + + if(esVal && field=="loudong_count" && esVal!=dbVal){ + newVal = FiledStrand.processLoudongCount(esVal) + } + + if(field=="estate_charge" && esVal!=dbVal){ + def numVal = FiledStrand.getNumber(esVal) + if(numVal && numVal.toString().toDouble()!=dbVal){ + newVal = FiledStrand.processEstateCharge(dbObj.city, numVal, dbObj.estate_type2) + newVal = newVal.toString() + } + } + if(field=="car_site_count"){ + def numVal = FiledStrand.getNumber(esVal) + if(numVal && numVal.toString().toInteger()!=dbVal){ + newVal = FiledStrand.processCarSite(numVal) + } + } + } + } + if(newVal){ + lastValueMap.put(field, newVal) + + //ÒÔÏÂΪͳ¼Æ¸÷ÍøÕ¾¸÷×ֶεĸüÐÂÇé¿ö + def fieldStatMap = statMap.get(esData.source) + if(!fieldStatMap){ + fieldStatMap = [:] + statMap.put(esData.source, fieldStatMap) + } + def count = fieldStatMap.get(field) + if(!count){ + fieldStatMap.put(field, 1) + }else{ + fieldStatMap.put(field, count + 1) + } + } + } + } + } + return lastValueMap + } + + def findThirdMatchDist(source){ + def query = new BasicDBObject("source",source).append("old_match_way", 1) + def keys = new BasicDBObject() + keys.put("url", 1) + keys.put("old_match_id", 1) + keys.put("old_match_city", 1) + keys.put("old_match_district", 1) + keys.put("old_match_name", 1) + def idsMap = [:] + def dbcursor = thirdSeaweedMappingColl.find(query, keys) + for(def db : dbcursor){ + if(!db.old_match_id && db.old_match_name){ + def dbo = CommonDatautils.findDistrict(db.old_match_city, db.old_match_district, db.old_match_name, "district") + if(dbo){ + idsMap.put(dbo._id.toString(), db.url) + } + }else{ + idsMap.put(db.old_match_id, db.url) + } + + } + return idsMap + } + + static def findCommunities(url){ + if(!url){ + return null + } + QueryBuilder queryBuilder = QueryBuilders.boolQuery().must(QueryBuilders.termQuery("url", url)) + def rets = [] + def datas = null + try{ + datas = ElasticUtils.executeSimpleQuery("192.168.0.206", "community", queryBuilder); + }catch(Exception e){ + findCommunities(url) + } + def data = [:] + if(datas) { + for (int k = 0; k < datas.size(); k++) { + def d = datas[k]; + data.put("household_count", d.households) + data.put("loudong_count", d.loudong_cnt) + data.put("developer", d.developer) + data.put("estate_company", d.property_company) + data.put("estate_charge", d.property_fee) + data.put("car_site_count", d.parking_cnt) + } + } + return data; + } +} diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/es/EsMonthHouseStat.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/es/EsMonthHouseStat.groovy index 9be75aeb0..e07ac0739 100644 --- a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/es/EsMonthHouseStat.groovy +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/es/EsMonthHouseStat.groovy @@ -26,7 +26,8 @@ class EsMonthHouseStat { // task.statHouseUpdateCount() // task.statDistHouse() - task.statRent() +// task.statRent() + task.statOfficeHouse() } def statRent(){ @@ -201,6 +202,51 @@ class EsMonthHouseStat { },0) } + def statOfficeHouse(){ + def citys = CommonDatautils.findAllCity() + def allLists = [] + allLists << ["³ÇÊÐ", "½üÒ»Äêд×ÖÂ¥³öÊÛÁ¿", "д×ÖÂ¥Á¿", "½üÒ»Äê³öÊÛ·¿Ô´Á¿´óÓÚ3µÄд×ÖÂ¥Á¿", "´óÓÚ3д×ÖÂ¥Á¿Õ¼±È"] + citys.each{c-> + def count = findHouseCountByCat(c, "office_sell",20240101, 20250201) + + def districts = CommonDatautils.findAllDistricts(c, "office", ["city", "region", "name", "alias"]); + def disthouseCount = 0 + for(def dist : districts){ + def alias = [] + if(dist.alias){ + if(!dist.alias.contains(dist.name)){ + dist.alias << dist.name + } + alias = dist.alias + }else{ + alias << dist.name + } + + def distCount = 0 + if(count){ + distCount = findHouseCountByCat(dist.city, dist.region, alias, 20240101, 20250201, "office_sell") + if(distCount && distCount>=3){ + disthouseCount++ + } + } +// println dist.city+" "+dist.region+" "+dist.name+" "+distCount + } + + println "disthouseCount:"+disthouseCount +// println districts.size() + def precent = 0 + if(districts){ + precent = DataHandleUtils.getDoubleRound(2, disthouseCount*100.0/districts.size()) + } + def row = [c , count, districts.size(), disthouseCount, precent+"%"] + println row + allLists << row + } + + ExcelUtils.write("D:\\Êý¾Ý\\д×ÖÂ¥\\È«¹úд×ÖÂ¥Çé¿öÕ¼±Èͳ¼Æ.xlsx", allLists, "д×ÖÂ¥Çé¿ö") + + } + def findHouseCount(def city, def region, def alias, def startDate, def endDate){ def aliasStr = null; @@ -219,6 +265,23 @@ class EsMonthHouseStat { return total } + def findHouseCountByCat(def city, def region, def alias, def startDate, def endDate, cat){ + def aliasStr = null; + def total = 0 + try{ + aliasStr = escapeExprSpecialWord(alias.join("','")) + String sql = "select count(*) as c from latest_seawater where cat='${cat}' and city='${city}' and p_date >= ${startDate} and p_date<${endDate} and region='${region}' and district_name in ('${aliasStr}') " + + ElasticUtils.executeSqlQuery(sql,{data-> + total = data.c + }) + }catch(Exception e){ + e.printStackTrace() + } + + return total + } + /** * תÒå×Ö·û´®ÖеÄÌØÊâ×Ö·û * ½ö¹ýÂËLucene regexps, ÆäËûµÄÎðÓà @@ -240,6 +303,17 @@ class EsMonthHouseStat { } + def findHouseCountByCat(def city, def cat, def startDate, def endDate){ + + String sql = "select count(*) as c from latest_seawater where cat='${cat}' and city='${city}' and p_date >= ${startDate} and p_date<${endDate} " + def total = 0 + ElasticUtils.executeSqlQuery(sql,{ data-> + total = data.c + }) + return total + } + + diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/fjwPriceBaseData/FjwThirdPartyPriceBatch.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/fjwPriceBaseData/FjwThirdPartyPriceBatch.groovy index f1925938e..892ebfea5 100644 --- a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/fjwPriceBaseData/FjwThirdPartyPriceBatch.groovy +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/fjwPriceBaseData/FjwThirdPartyPriceBatch.groovy @@ -32,8 +32,11 @@ class FjwThirdPartyPriceBatch extends BaseBatch { static final DBCollection AVERAGE_STATISTICS = MongoUtils.getCollectionByName("fangjia", "average_statistics", "192.168.0.43") DBCollection DIST_SELL_STAT = MongoUtils.getCollectionByName("fangjia_stat", "district_stat", "mongo.db.fangjia.com") - def sourceMap = ["Öî¸ðÕÒ·¿":"01", "°²¾Ó¿Í":"02","·¿ÌìÏÂ":"03","Á´¼Ò":"04","³ÇÊмҾÓ":"05","ÂóÌï":"06","±´¿Ç":"07","ÌÔ·¿365":"08","ÖÐÔ­":"09","Íò©Ê¿":"10","Q·¿":"11","·¿Ì½":"12", - "·¿¶à¶à":"13","ÎÒ°®ÎÒ¼Ò":"14","ìûÌ©Êý¾Ý":"15","¼ªÎÝÍø":"16","ÀÖ¾Ó":"17","21ÊÀ¼Í":"18","·¿²ú³¬ÊÐ":"19","58ͬ³Ç":"20"] + def sourceMap = ["Öî¸ðÕÒ·¿":"01", "°²¾Ó¿Í":"02","·¿ÌìÏÂ":"03","Á´¼Ò":"04","³ÇÊмҾÓ":"05","ÂóÌï":"06","±´¿Ç":"07", + "ÌÔ·¿365":"08","ÖÐÔ­":"09","Íò©Ê¿":"10","Q·¿":"11","·¿Ì½":"12","·¿¶à¶à":"13","ÎÒ°®ÎÒ¼Ò":"14", + "ìûÌ©Êý¾Ý":"15","¼ªÎÝÍø":"16","ÀÖ¾Ó":"17","21ÊÀ¼Í":"18","·¿²ú³¬ÊÐ":"19","58ͬ³Ç":"20", + "ÀÖÓмÒ":"21","ÐÒ¸£Àï":"22","Öйú·¿¼ÛÐÐÇé":"23","³£ÖÝס·¿":"24" + ] def pgsqlInstance = Sql.newInstance("jdbc:postgresql://192.168.0.235:5433/fangjia?stringtype=unspecified", @@ -269,6 +272,33 @@ class FjwThirdPartyPriceBatch extends BaseBatch { if(third.get("fccs_esf_price")){ price_map.fccs_avg_price = third.get("fccs_esf_price") } + if(third.get("csjj_esf_price")){ + price_map.csjj_avg_price = third.get("csjj_esf_price") + } + + if(third.get("leyoujia_esf_price")){ + price_map.leyoujia_avg_price = third.get("leyoujia_esf_price") + } + + if(third.get("c21_esf_price")){ + price_map.c21_avg_price = third.get("c21_esf_price") + } + + if(third.get("jiwu_esf_price")){ + price_map.jiwu_avg_price = third.get("jiwu_esf_price") + } + + if(third.get("xingfuli_esf_price")){ + price_map.xingfuli_avg_price = third.get("xingfuli_esf_price") + } + + if(third.get("zwfc_esf_price")){ + price_map.zwfc_avg_price = third.get("zwfc_esf_price") + } + + if(third.get("creprice_esf_price")){ + price_map.creprice_avg_price = third.get("creprice_esf_price") + } dataMap.updatetime = DateUtils.formatDateByPattern(new Date(), "yyyy-MM-dd HH:mm:ss") allRows << dataMap } @@ -317,6 +347,20 @@ class FjwThirdPartyPriceBatch extends BaseBatch { web = "ÎÒ°®ÎÒ¼Ò" }else if(k=="fccs_avg_price"){ web = "·¿²ú³¬ÊÐ" + }else if(k=="csjj_avg_price"){ + web = "³ÇÊоӼÒ" + }else if(k=="leyoujia_avg_price"){ + web = "ÀÖÓмÒ" + }else if(k=="c21_avg_price"){ + web = "C21" + }else if(k=="jiwu_avg_price"){ + web = "¼ªÎÝÍø" + }else if(k=="xingfuli_avg_price"){ + web = "ÐÒ¸£Àï" + }else if(k=="creprice_avg_price"){ + web = "Öйú·¿¼ÛÐÐÇé" + }else if(k=="zwfc_avg_price"){ + web = "³£ÖÝס·¿" } ret << sourceMap.get(web) @@ -470,6 +514,33 @@ class FjwThirdPartyPriceBatch extends BaseBatch { dataMap.put("fccs_esf_price", db.get("fccs_esf_price")) } + if(!dataMap.get("csjj_esf_price") && db.get("csjj_esf_price") && db.get("csjj_esf_price")>3000){ + dataMap.put("csjj_esf_price", db.get("csjj_esf_price")) + } + + if(!dataMap.get("leyoujia_esf_price") && db.get("leyoujia_esf_price") && db.get("leyoujia_esf_price")>3000){ + dataMap.put("leyoujia_esf_price", db.get("leyoujia_esf_price")) + } + + if(!dataMap.get("c21_esf_price") && db.get("c21_esf_price") && db.get("c21_esf_price")>3000){ + dataMap.put("c21_esf_price", db.get("c21_esf_price")) + } + + if(!dataMap.get("jiwu_esf_price") && db.get("jiwu_esf_price") && db.get("jiwu_esf_price")>3000){ + dataMap.put("jiwu_esf_price", db.get("jiwu_esf_price")) + } + + if(!dataMap.get("xingfuli_esf_price") && db.get("xingfuli_esf_price") && db.get("xingfuli_esf_price")>3000){ + dataMap.put("xingfuli_esf_price", db.get("xingfuli_esf_price")) + } + + if(!dataMap.get("creprice_esf_price") && db.get("creprice_esf_price") && db.get("creprice_esf_price")>3000){ + dataMap.put("creprice_esf_price", db.get("creprice_esf_price")) + } + + if(!dataMap.get("zwfc_esf_price") && db.get("zwfc_esf_price") && db.get("zwfc_esf_price")>3000){ + dataMap.put("zwfc_esf_price", db.get("zwfc_esf_price")) + } // if(db.zhugezhaofang_esf_price || db.anjuke_esf_price ||db.soufang_esf_price || db.lianjia_esf_price || db.cityhouse_esf_price || db.maitian_esf_price || db.beike_esf_price || db.get("365house_esf_price") || db.zhongyuan_esf_price || db.tuboshi_esf_price || db.qfang_esf_price || db.fangtan_esf_price || db.fangduoduo_esf_price || db.get("5i5j_esf_price")){ // map.put(key, db) // } diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/images/AddDistImagesBatch.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/images/AddDistImagesBatch.groovy index 9ba1fe9ca..e545a78e6 100644 --- a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/images/AddDistImagesBatch.groovy +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/images/AddDistImagesBatch.groovy @@ -38,8 +38,8 @@ class AddDistImagesBatch extends BaseBatch{ @Override public void process(Object args) { -// def mdate = DateUtils.formatDateByPattern(DateUtils.getFirstDayOfMonth(new Date(), -1), "yyyy-MM-dd") def mdate = DateUtils.getFirstDayOfMonth(new Date(), -1) +// def mdate = DateUtils.getFirstDayOfMonth(new Date(), -1) def citys = CommonUtils.findAllCity() citys.each {city-> def communitys = findAllEsData2(city, mdate) @@ -47,14 +47,13 @@ class AddDistImagesBatch extends BaseBatch{ //µÚÈý·½Æ¥ÅäÐ¡Çø matchCommunitys(communitys) } + + statImgCount() } - - - def findAllEsData2(city, mdate){ QueryBuilder date_range = QueryBuilders.rangeQuery("m_date").from(mdate.getTime()).includeLower(true) - - QueryBuilder queryBuilder = QueryBuilders.boolQuery().must(QueryBuilders.termQuery("city", city)).must(QueryBuilders.termQuery("source", "°²¾Ó¿ÍС³ÌÐò")) + //°²¾Ó¿ÍС³ÌÐò + QueryBuilder queryBuilder = QueryBuilders.boolQuery().must(QueryBuilders.termQuery("city", city)).must(QueryBuilders.termQuery("source", "±´¿ÇÕÒ·¿")) .must(date_range).must(date_range) def rets = [] @@ -106,41 +105,69 @@ class AddDistImagesBatch extends BaseBatch{ def total = communitys.size() for(def i=0;i + floor_count = floor_count + v.size() + } + } + } + println out_pics_count + println floor_count + } + + } diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/meishubao/MsbPocTest.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/meishubao/MsbPocTest.groovy index 99b913307..e58c11ff5 100644 --- a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/meishubao/MsbPocTest.groovy +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/meishubao/MsbPocTest.groovy @@ -13,18 +13,18 @@ class MsbPocTest { task.run(); } def run(){ - def inputfile = "D:\\Êý¾Ý\\½¨ÐÐ\\·¿²ú¹ÀÖµ\\_ÒµÎñ5Ô·Ýϵͳ·´À¡ÎÊÌâ¼Û¸ñºË²é20240416-20240516 - ¹úÐÅ´ï0524.xlsx" + def inputfile = "D:\\Êý¾Ý\\½¨ÐÐ\\·¿²ú¹ÀÖµ\\·¿Ñ¶Í¨10Ô¼۸ñºË²é_1126-FXTÌá½»½á¹û20241205.xlsx" // def inputfile = "D:\\Êý¾Ý\\ÃÀÊõ±¦\\ÃÀÊõ±¦²âÊÔÊý¾Ý(Æ¥ÅäV2).xlsx"//ÃÀÊõ±¦²âÊÔÊý¾Ý(Æ¥Åä).xlsx // standard(inputfile) // match(inputfile) -// matchOld(inputfile) + matchOld(inputfile) // addPrice("D:\\Êý¾Ý\\ÃÀÊõ±¦\\ÃÀÊõ±¦²âÊÔÊý¾Ý(¼Û¸ñ).xlsx") -// test("D:\\Êý¾Ý\\ÃÀÊõ±¦\\test2.xlsx") +// test("D:\\Êý¾Ý\\ÃÀÊõ±¦\\FiveLevelTest.xlsx") // cityPrice() // mergeMatchPrice("D:\\Êý¾Ý\\ÃÀÊõ±¦\\ÃÀÊõ±¦-нӿڼ۸ñ.xlsx") - addCCBPrice(inputfile) +// addCCBPrice(inputfile) } def cityPrice(){ @@ -69,24 +69,24 @@ class MsbPocTest { def matchOld(path){ ExcelUtils.multiThreadingModify(path, { row -> - if(!row['Y'] && row['G']){ + if(!row['AD'] ){ def city = row['C'] def region = null //row['D'] - def name = row['E'] - def address = row['G'] + def name = null// row['E'] + def address = row['D'] println "[match] city:"+city+" region:"+region+" address:"+address def jsonObject = OpenApiClient.addressMatch(city, address, "property", false, region, name) if(jsonObject != null && jsonObject.precise!=-1) { - row['Y'] = jsonObject.get("id") - row['Z'] = jsonObject.get("city") - row['AA'] = jsonObject.get("district") - row['AB'] = jsonObject.get("name") - row['AC'] = jsonObject.get("propertyType") + row['AD'] = jsonObject.get("id") + row['AE'] = jsonObject.get("city") + row['AF'] = jsonObject.get("district") + row['AG'] = jsonObject.get("name") + row['AH'] = jsonObject.get("propertyType") // row['X'] = jsonObject.get("credit") } } - }) + },1) } @@ -114,7 +114,7 @@ class MsbPocTest { if(!row['Y']){ def city = row['C'] def region = null //row['B'] - def address = row['G'] //row['G']//row['F'] + def address = row['D'] //row['G']//row['F'] println "[match] city:"+city+" region:"+region+" address:"+address def jsonObject = FangjiaClientUtils.newMatch(city, address, "property", false) @@ -125,7 +125,7 @@ class MsbPocTest { row['AB'] = jsonObject.get("name") } } - }) + },1) } diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/poc/AddPriceTest.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/poc/AddPriceTest.groovy index d314427a9..5cd666999 100644 --- a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/poc/AddPriceTest.groovy +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/poc/AddPriceTest.groovy @@ -38,9 +38,9 @@ class AddPriceTest { task.run(); } def run(){ - def filePath = "D:\\Êý¾Ý\\½¨ÐÐ\\·¿²ú¹ÀÖµ\\202410²âÊÔÆ«²î½Ï´ó°¸Àýͳ¼ÆÊý¾Ýtest.xlsx" - addGXDPrice(filePath) -// addCcbPrice(filePath) + def filePath = "D:\\Êý¾Ý\\¼Û¸ñ\\»ÝÖÝ.xlsx" +// addGXDPrice(filePath) + addCcbPrice(filePath) // addThirdPrice(filePath) // addFjwPrice(filePath) // exportPkPrice() @@ -174,26 +174,28 @@ class AddPriceTest { def addCcbPrice(filepath){ def cityCodeDataMap = CcbCommonUtils.findCityCodeValue() ExcelUtils.multiThreadingModify(filepath,{ d-> - if(d['U']){ - def cityId = cityCodeDataMap.get(d['V']) - def map = findAvgPrice(d['U'], cityId) + if(d['A']){ + def cityId = cityCodeDataMap.get(d['B']) + def map = findAvgPrice(d['A'], cityId) if(map){ - d['H'] = map.avg_price - d['I'] = map.calc_type + d['I'] = map.avg_price + d['J'] = map.month +// d['H'] = map.calc_type // d['AM'] = map.credit_value } -// def newPriceMap = findNewFjwAvgPrice(d['U'], cityId) -// if(newPriceMap){ -// d['Q'] = newPriceMap.avg_price -// } + def newPriceMap = findNewFjwAvgPrice(d['A'], cityId) + if(newPriceMap){ + d['G'] = newPriceMap.avg_price + d['H'] = newPriceMap.month + } } }) } def findAvgPrice(def commid, def cityid){ - def sql = "SELECT gujia_bds_clc_avprc,gujia_bds_clmtd,gujiabds_clc_yrmo_val,gujia_bds_cfdc_dgr from t_app_p9pha_plda.avm_community_base_price_gj_h where urbn_id='${cityid}' and gujia_bds_id='${commid}' and gujiabds_clc_yrmo_val=202409 order by gujiabds_clc_yrmo_val desc limit 1" + def sql = "SELECT gujia_bds_clc_avprc,gujia_bds_clmtd,gujiabds_clc_yrmo_val,gujia_bds_cfdc_dgr from t_app_p9pha_plda.avm_community_base_price_gj_h where urbn_id='${cityid}' and gujia_bds_id='${commid}' order by gujiabds_clc_yrmo_val desc limit 1" def map = [:] pgsqlInstance.eachRow(sql, { r -> map.avg_price = r.gujia_bds_clc_avprc @@ -213,7 +215,7 @@ class AddPriceTest { def findNewFjwAvgPrice(def commid, def cityid){ - def sql = "SELECT gujia_bds_clc_avprc,gujia_bds_clmtd,gujiabds_clc_yrmo_val,gujia_bds_cfdc_dgr from price_stat.avm_community_base_price where urbn_id='${cityid}' and gujia_bds_id='${commid}' and gujiabds_clc_yrmo_val=202409 order by gujiabds_clc_yrmo_val desc limit 1" + def sql = "SELECT gujia_bds_clc_avprc,gujia_bds_clmtd,gujiabds_clc_yrmo_val,gujia_bds_cfdc_dgr from price_stat.avm_community_base_price where urbn_id='${cityid}' and gujia_bds_id='${commid}' order by gujiabds_clc_yrmo_val desc limit 1" def map = [:] pgsqlInstance235.eachRow(sql, { r -> map.avg_price = r.gujia_bds_clc_avprc @@ -270,14 +272,14 @@ class AddPriceTest { def addGXDPrice(filepath){ ExcelUtils.multiThreadingModify(filepath, { d -> - if (!d['B']) { + if (!d['H']) { def dist = CommonDatautils.findDistrictById(d['A']) if(dist){ def gxdPrice = findGXDPrice(dist.city, dist.region, dist.name) // def gxdPrice = findGXDPrice(d['D'], d['E'], d['C']) if(gxdPrice){ - d['B'] = gxdPrice.price - d['C'] = DateUtils.formatDateByPattern(gxdPrice.c_date, "yyyy-MM-dd") + d['H'] = gxdPrice.price + d['I'] = DateUtils.formatDateByPattern(gxdPrice.c_date, "yyyy-MM-dd") } } @@ -305,11 +307,11 @@ class AddPriceTest { ExcelUtils.multiThreadingModify(path,{d-> // if(!d['L']){ // if(d['J'] instanceof String){ - def dist = CommonDatautils.findDistrictById(d['AJ']) + def dist = CommonDatautils.findDistrictById(d['A']) if(dist){ // d['A'] = dist.city // d['B'] = dist.region - d['E'] = dist.name +// d['E'] = dist.name // d['D'] = dist.status // d['E'] = dist.name_cat // d['F'] = dist.estate_type2 @@ -318,9 +320,9 @@ class AddPriceTest { // d['N'] = dist.region def dbo = CommonDatautils.queryFirstDistrictPrice(dist.city, dist.region, dist.name) if(dbo){ - d['G'] = dbo.avg_price + d['E'] = dbo.avg_price_2b // d['X'] = dbo.cal_type -// d['E'] = dbo.avg_price_2b +// d['E'] = dbo.avg_price } } // } diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/xiamen/RelatedTaiWanBatch.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/xiamen/RelatedTaiWanBatch.groovy index e44d4424e..5cf2d132a 100644 --- a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/xiamen/RelatedTaiWanBatch.groovy +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/xiamen/RelatedTaiWanBatch.groovy @@ -7,6 +7,7 @@ import com.fangjia.script.commData.CommonDatautils import com.fangjia.script.common.DataHandleUtils import com.fangjia.script.gj.ccb.FileUtils import com.fangjia.script.looplineinfo.InsidePolygon +import com.fangjia.script.looplineinfo.Point import com.fangjia.script.util.DateUtils import com.fangjia.script.util.MongoUtils import com.fangjia.script.yinjihaun.amap.GaoDeApiUtils @@ -17,7 +18,7 @@ import com.mongodb.DBCollection */ -@BatchOwner(Watcher.GaoJuan) +//@BatchOwner(Watcher.GaoJuan) class RelatedTaiWanBatch extends BaseBatch{ @@ -69,7 +70,9 @@ class RelatedTaiWanBatch extends BaseBatch{ if(r.lon && r.lat){ for(def m : zimaoqu_range_datas){ // def flag = InsidePolygon.isInArea(r.lon, r.lat, InsidePolygon.createPoint5(m.shape)) - def flag = InsidePolygon.isPtInPoly(r.lon, r.lat, InsidePolygon.createPoint5(m.shape)) + List> pointsList = InsidePolygon.createPoint4(m.shape) +// def flag = InsidePolygon.isPtInPoly(r.lon, r.lat, pointsList) + def flag = InsidePolygon.isInArea(r.lon, r.lat, pointsList) if(flag){ resKey = m.name break diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/xiamen/SeaweedDataSynch.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/xiamen/SeaweedDataSynch.groovy index e78bc7018..41ccc9e38 100644 --- a/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/xiamen/SeaweedDataSynch.groovy +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/gj/xiamen/SeaweedDataSynch.groovy @@ -226,16 +226,17 @@ class SeaweedDataSynch extends BaseBatch{ for(def key : dist.mapping_alias){ if(key && !key.toString().equals("null")){ aliasNames << key - if(aliasNames.size()>5){ - map.alias = aliasNames - break; - }else{ - if(aliasNames){ - map.alias = aliasNames - } - } +// if(aliasNames.size()>5){ +// map.alias = aliasNames +// break; +// }else{ +// if(aliasNames){ +// map.alias = aliasNames +// } +// } } } + map.alias = aliasNames } if(dist.addr_alias){ @@ -243,16 +244,17 @@ class SeaweedDataSynch extends BaseBatch{ for(def key : dist.addr_alias){ if(key && !key.toString().equals("null")){ names << key - if(names.size()>5){ - map.addr_alias = names - break; - }else{ - if(names){ - map.addr_alias = names - } - } +// if(names.size()>5){ +// map.addr_alias = names +// break; +// }else{ +// if(names){ +// map.addr_alias = names +// } +// } } } + map.addr_alias = names } map.category = dist.cat diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/looplineinfo/InPolygon.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/looplineinfo/InPolygon.groovy new file mode 100644 index 000000000..4d79373ca --- /dev/null +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/looplineinfo/InPolygon.groovy @@ -0,0 +1,132 @@ +package com.fangjia.script.looplineinfo + +import com.fangjia.script.common.DataHandleUtils + +import java.awt.geom.Point2D; + +class InPolygon { + + + public static List> createPoint(def pointList){ + List> alllist = new ArrayList<>(); + for(def pointArr : pointList){ + List list = new ArrayList<>(); + for(def arr : pointArr){ + double x = DataHandleUtils.getDoubleRound(6, arr[0]); + double y = DataHandleUtils.getDoubleRound(6, arr[1]); + Point2D.Double point = new Point2D.Double(x,y); + list.add(point); + } + alllist << list + } + return alllist + } + + public static def isInArea(Point2D.Double point, List> pointList){ + def flag = false; + for(List pointArr : pointList){ + flag = isPtInPoly(point, pointArr) + if(flag){ + break; + } + } + return flag; + } + + /** + * ÅжϵãÊÇ·ñÔÚ¶à±ßÐÎÄÚ + *

    + * Õû¸öËã·¨µÄ˼·Ϊ£º×÷µãƽÐÐÓÚyÖáµÄÉäÏߣ¬ÕâÑù¾Í¿ÉÒÔÖ±½Ó±È½Ï½»µãÊÇ·ñ´óÓÚµã(x,y)ÖÐyµÄÖµ£¬¿ÉÒÔ¼ò»¯Åжϡ£ + * + * @param point ¼ì²âµã + * @param pts ¶à±ßÐεĶ¥µã + * @return µãÔÚ¶à±ßÐÎÄÚ·µ»Øtrue, ·ñÔò·µ»Øfalse + */ + public static boolean isPtInPoly(Point2D.Double point, List pts) { + int polygonSidesCount = pts.size(); + //Èç¹ûµãλÓÚ¶à±ßÐεĶ¥µã»ò±ßÉÏ£¬Ò²Ëã×öµãÔÚ¶à±ßÐÎÄÚ£¬Ö±½Ó·µ»Øtrue + boolean boundOrVertex = true; + // ÉäÏßÓë¶à±ßÐÎÏཻµÄ´ÎÊý + int intersectCount = 0; + //¸¡µãÀàÐͼÆËãʱºòÓë0±È½ÏʱºòµÄÈݲî + double precision = 2e-10; + // ÏàÁÚÁ½µã + Point2D.Double p1, p2; + // µ±Ç°µã + Point2D.Double p = point; + // Ïß¶ÎÆðµã + p1 = pts.get(0); + for (int i = 1; i <= polygonSidesCount; ++i) { + //°´ÕÕµã¼ÈëµÄ˳ÐòÒÀ´Î¼ì²éÏàÁÚÁ½µã×é³ÉµÄÏ߶κ͵±Ç°µÄµãµÄ¹ØÏµ¡£ + if (p.equals(p1)) { + //Èç¹ûµ±Ç°µã¾ÍÊǶà±ßÐεĶ¥µãÖ®Ò»£¬Ö±½Ó·µ»Ø¡£ + return boundOrVertex; + } + // Ïß¶ÎÖÕµã + p2 = pts.get(i % polygonSidesCount); + if (p.x < Math.min(p1.x, p2.x) || p.x > Math.max(p1.x, p2.x)) { + //µãÔÚxÖáÉϵÄÓ³É䣬Ã÷ÏÔ³¬³öÁËÏß¶ÎÔÚxÖáÉϵÄͶӰ¡£´Ëʱ³å×ÅÉÏ×öÉäÏߣ¬¿Ï¶¨Ã»Óн»µã£¬Ö±½ÓÌø¹ý¡£ + p1 = p2; + continue; + } + if (p.x > Math.min(p1.x, p2.x) && p.x < Math.max(p1.x, p2.x)) { + // µ±Ç°µãÔÚÏß¶ÎÓÚxÖáÉϵÄͶӰÄÚ + if (p.y <= Math.max(p1.y, p2.y)) { + //µ±Ç°µãµÄ y ×ø±êСÓÚ Ï߶ζÔyÖáͶӰµÄ×î´óÖµ + if (p1.x == p2.x && p.y >= Math.min(p1.y, p2.y)) { + // ÈôÏß¶ÎͬÑùÊÇÆ½ÐÐÓÚyÖᣬÔò¿ÉÒԶ϶¨£¬µ±Ç°µã£¬ÔÚ¶à±ßÐεÄÕâÌõ´¹Ö±ÓÚxÖáµÄ±ßÉÏ¡£ + return boundOrVertex; + } + if (p1.y == p2.y) { + // ÈôÏß¶ÎΪƽÐÐÓÚxÖáµÄˮƽÏß + if (p1.y == p.y) { + //µ±Ç°µãÕýºÃλÓÚ¸ÃˮƽÏßÉÏ£¬Ö±½Ó·µ»Ø¸ÃµãλÓÚ¶à±ßÐεÄÒ»Ìõ±ßÉÏ¡£ + return boundOrVertex; + } else { + //Èç¹ûµ±Ç°µãÔÚˮƽÏßÒÔÏ£¬Ôö¼ÓÒ»¸ö½»µã¡£ + ++intersectCount; + } + } else { + // Èç¹û²»ÊÇˮƽÏߣ¬ÔòÓÃÁ½µãʽÇóµ±Ç°µãµÄx´øÈë¶à±ßÐÎÏ߶εÄÖ±Ïß·½³Ìºó£¬¶ÔÓ¦µÄyµÄ×ø±ê + double xInSideLineFormulaResultY = (p.x - p1.x) * (p2.y - p1.y) / (p2.x - p1.x) + p1.y; + if (Math.abs(p.y - xInSideLineFormulaResultY) < precision) { + // Îó²îÔÊÐí·¶Î§ÄÚ£¬¸Äµã¾ÍÔÚÏß¶ÎÉÏ£¬Ôò±íÃ÷£¬¸ÃµãλÓÚ¶à±ßÐεÄÒ»¸ö±ßÉÏ¡£ + return boundOrVertex; + } + + if (p.y < xInSideLineFormulaResultY) { + // Èç¹ûÏß¶ÎÉÏÈ¡µÃµÄy±Èµ±Ç°µãµÄyÒª´ó£¬µ±Ç°×öÏòÉϵÄÉäÏߣ¬¿Ï¶¨½»ÓÚÉÏ·½µÄÒ»¸öµã¡£ + ++intersectCount; + } + } + } + } else { + // µ±Ç°µã²»ÔÚÏß¶ÎͶӰµ½xÖáµÄÇø¼äÖÐ + if (p.x == p2.x && p.y <= p2.y) { + // µ«Ç¡ºÃλÓÚÏß¶ÎÖÕµãµÄx×ø±ê¶ÔÓ¦µÄƽÐÐÓÚyÖáÉϵÄÏßÉϵĵÍÓÚÖÕµãyµÄÒ»µã + // ´Ëʱ¼ì²éÏÂÒ»µãÄÜ·ñ½«Æäx±ß½ç°üº¬¡£ + Point2D.Double p3 = pts.get((i + 1) % polygonSidesCount); + if (p.x >= Math.min(p1.x, p3.x) && p.x <= Math.max(p1.x, p3.x)) { + // Èôµ±Ç°µãµÄx×ø±êλÓÚ p1ºÍp3×é³ÉµÄÏ߶ιØÓÚxÖáµÄͶӰÖУ¬Ôò¼ÇΪ¸ÃµãµÄÉäÏßÖ»´©¹ý¶ËµãÒ»´Î¡£ + ++intersectCount; + } else { + // Èôµ±Ç°µãµÄx×ø±ê²»Äܰüº¬ÔÚp1ºÍp3×é³ÉµÄÏ߶ιØÓÚxÖáµÄͶӰÖУ¬ÔòµãÉäÏßͨ¹ýµÄÁ½ÌõÏß¶Î×é³ÉÁËÒ»¸öÍäÕ۵IJ¿·Ö£¬ + // ´ËʱÎÒÃǼÇÉäÏß´©¹ý¸Ã¶ËµãÁ½´Î + intersectCount += 2; + } + // ´ËÅжϵĺËÐÄ˼·ÊÇÓɵãÔÚÁ½ÌõÏ߶εÄÄÚ²¿»¹ÊÇÍⲿȥ˼¿¼µÃ³öµÄ + } + } + // ½øÐÐÏÂÒ»¸öÏ߶εÄÅÐ¶Ï + p1 = p2; + } + if (intersectCount % 2 == 0) { + //żÊýÔÚ¶à±ßÐÎÍâ + return false; + } else { + //ÆæÊýÔÚ¶à±ßÐÎÄÚ + return true; + } + } + +} diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/looplineinfo/InsidePolygon.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/looplineinfo/InsidePolygon.groovy index 58a13a34d..25f5c45ed 100644 --- a/projects/fangjia-script/src/main/groovy/com/fangjia/script/looplineinfo/InsidePolygon.groovy +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/looplineinfo/InsidePolygon.groovy @@ -324,4 +324,8 @@ class InsidePolygon { } return name; } + + + + } diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/majintao/test.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/majintao/test.groovy deleted file mode 100644 index 350ffa191..000000000 --- a/projects/fangjia-script/src/main/groovy/com/fangjia/script/majintao/test.groovy +++ /dev/null @@ -1,72 +0,0 @@ -package com.fangjia.script.majintao - -import com.fangjia.core.util.HttpRequest -import com.fangjia.script.util.ExcelUtils -import net.sf.json.JSONObject - - -String excelFilePath = "F:\\¹À¼Ò\\Îļþ\\±±½»Ëù\\testcopy1.xlsx"; -ExcelUtils.removeEmptyRow(excelFilePath) -ExcelUtils.singleThreadingModify(excelFilePath, { List items -> - - String comprehensiveUrl = "http://localhost:9180/comprehensiveQuery/houseValueInformation"; - String communityUrl = "http://open.fangjia.com/addrSvc/avgPrice"; - String valueUrl = "http://open.fangjia.com/property/addressEvaluate"; - String caseUrl = "http://open.fangjia.com/house/case"; - String poiUrl = "http://open.fangjia.com/district/addrFacilitys"; - - HttpRequest httpRequest = new HttpRequest(); - map = new HashMap() - - String city = items['A'] - String address = items['B'] - double size = items['C'] - - System.out.println(city + "---" + address + "----" + size); - - map.put("city", city) - map.put("address", address) - map.put("size", size.toString()) - map.put("strctureArea", size.toString()) - map.put("token", "F54F52381C49BB9EB4A33EB1B65604AE4B71A28AEE53518A94A2F360408B9056D57553931D15CE6DDE765562DAD286BA38E05A4CDAFC51C3D527A4959BF8E75A3B95DB7108FCEA340DDE61925616DB55118E1851E67D83EAD800460D100D6B667A4ED8EE67C8F7FB") - - if (!address.contains("%")) { - // ·¢ËÍHTTPÇëÇó - long start - long end - -// start = System.currentTimeMillis(); -// httpRequest.getJsonContent(communityUrl, map, "UTF-8") -// -// -// end = System.currentTimeMillis(); -// items['D'] = String.valueOf(end - start); -// -// start = System.currentTimeMillis(); -// httpRequest.getJsonContent(valueUrl, map, "UTF-8") -// end = System.currentTimeMillis(); -// items['E'] = String.valueOf(end - start); -// -// start = System.currentTimeMillis(); -// httpRequest.getJsonContent(caseUrl, map, "UTF-8") -// end = System.currentTimeMillis(); -// items['F'] = String.valueOf(end - start); -// -// start = System.currentTimeMillis(); -// httpRequest.getJsonContent(poiUrl, map, "UTF-8") -// end = System.currentTimeMillis(); -// items['G'] = String.valueOf(end - start); - - start = System.currentTimeMillis(); - def content = httpRequest.getJsonContent(comprehensiveUrl, map, "UTF-8") - end = System.currentTimeMillis(); - items['H'] = String.valueOf(end - start); - println content.get("msg") - if(content.get("msg").contains("¸ÃµØÖ·²»Ö§³Ö¹À¼Û£¡")) { - items['I'] = "¸ÃµØÖ·²»Ö§³Ö¹À¼Û£¡" - } - } - - -}) - diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/majintao/test2.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/majintao/test2.groovy deleted file mode 100644 index 2c6e2d2ea..000000000 --- a/projects/fangjia-script/src/main/groovy/com/fangjia/script/majintao/test2.groovy +++ /dev/null @@ -1,4 +0,0 @@ -import org.bson.types.ObjectId - -a = new ObjectId() -print(a) \ No newline at end of file diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/trade/CopyOpenUriLog.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/sync/CopyOpenUriLog.groovy similarity index 66% rename from projects/fangjia-script/src/main/groovy/com/fangjia/script/trade/CopyOpenUriLog.groovy rename to projects/fangjia-script/src/main/groovy/com/fangjia/script/sync/CopyOpenUriLog.groovy index 4b40b89e0..c00c4a79b 100644 --- a/projects/fangjia-script/src/main/groovy/com/fangjia/script/trade/CopyOpenUriLog.groovy +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/sync/CopyOpenUriLog.groovy @@ -1,28 +1,16 @@ -package com.fangjia.script.trade - - -import java.util.regex.Matcher - +package com.fangjia.script.sync +import com.fangjia.core.Constants import com.fangjia.script.BaseBatch; import com.fangjia.script.BatchOwner -import com.fangjia.script.util.DateUtils; - -import java.util.regex.Pattern - -import org.apache.commons.lang.StringUtils; - -import com.fangjia.core.util.StringUtil; -import com.fangjia.datastore.driver.DSCollection; -import com.fangjia.datastore.driver.DSCursor -import com.fangjia.datastore.driver.DataStore +import com.fangjia.script.util.DateUtils import com.mongodb.BasicDBObject import com.mongodb.DBCollection; import com.mongodb.DBObject -import com.fangjia.script.util.MongoUtils; +import com.fangjia.core.util.MongoUtils; import com.fangjia.script.Watcher; import com.mongodb.Bytes -import org.apache.commons.io.FileUtils + /** * ½«ÏßÉÏopen uriÊý¾Ýͬ²½µ½192.168.0.60ÉÏ * @author gaojuan @@ -31,7 +19,7 @@ import org.apache.commons.io.FileUtils class CopyOpenUriLog extends BaseBatch{ - static DBCollection DESC_OPEN = MongoUtils.getCollectionByName("business", "open_uri_log", "seawater.mongo.db.fangjia.com", 27020) + static DBCollection DESC_OPEN = MongoUtils.getDbCollection(Constants.SEAWATER_MONGO_URI, "business", "open_uri_log") public static final DBCollection SOURCE_OPEN = MongoUtils.getCollectionByName("business", "open_uri_log", "log.mongo.db.fangjia.com", 52002) static main(String[] args){ runBatch(new CopyOpenUriLog(), args) diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/thirdPriceCrawl/DataStandardBatch.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/thirdPriceCrawl/DataStandardBatch.groovy index b57cdd659..d8efa9ac3 100644 --- a/projects/fangjia-script/src/main/groovy/com/fangjia/script/thirdPriceCrawl/DataStandardBatch.groovy +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/thirdPriceCrawl/DataStandardBatch.groovy @@ -1062,6 +1062,7 @@ class DataStandardBatch extends BaseBatch{ q.put("s_date", SHORT_DATE); DBObject udata2 = new BasicDBObject() + udata2.put("match_id", district._id.toString()); udata2.put("match_city", district.city); udata2.put("match_region", district.region); udata2.put("match_name", district.name); diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/thirdPriceCrawl/SynchDistrictPrice.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/thirdPriceCrawl/SynchDistrictPrice.groovy index 5f07adb27..1b9e9e1e1 100644 --- a/projects/fangjia-script/src/main/groovy/com/fangjia/script/thirdPriceCrawl/SynchDistrictPrice.groovy +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/thirdPriceCrawl/SynchDistrictPrice.groovy @@ -27,7 +27,9 @@ class SynchDistrictPrice extends BaseBatch{ // "¼ªÎÝ":"¼ªÎÝ","365ÌÔ·¿":"365ÌÔ·¿","ÎÒ°®ÎÒ¼Ò":"ÎÒ°®ÎÒ¼Ò","Öî¸ðÕÒ·¿APP":"Öî¸ðÕÒ·¿","±´¿Ç":"±´¿ÇÕÒ·¿","Á´¼Ò":"Á´¼Ò","Q·¿":"Q·¿","ÂóÌï":"ÂóÌï", // "ÖÐÔ­µØ²ú":"ÖÐÔ­µØ²ú","°²¾Ó¿ÍС³ÌÐò":"°²¾Ó¿Í","ËÑ·¿":"ËÑ·¿","ÀÖÓмÒ":"ÀÖÓмÒ","C21":"C21","³ÇÊз¿²ú":"³ÇÊз¿²ú","Íò©Ê¿PC¶Ë":"Íò©Ê¿" // def esSources = ["ËÑ·¿":"ËÑ·¿"] - def esSources = ["ÎÒ°®ÎÒ¼Ò":"ÎÒ°®ÎÒ¼Ò","Íò©Ê¿PC¶Ë":"Íò©Ê¿","¼ªÎÝ":"¼ªÎÝ","±´¿ÇÕÒ·¿":"±´¿ÇÕÒ·¿","ÀÖÓмÒ":"ÀÖÓмÒ","365ÌÔ·¿":"365ÌÔ·¿","Öî¸ðÕÒ·¿APP":"Öî¸ðÕÒ·¿","Á´¼Ò":"Á´¼Ò","Q·¿":"Q·¿","ÂóÌï":"ÂóÌï","ÖÐÔ­µØ²ú":"ÖÐÔ­µØ²ú","°²¾Ó¿ÍС³ÌÐò":"°²¾Ó¿Í","ËÑ·¿":"ËÑ·¿","C21":"C21","³ÇÊз¿²úС³ÌÐò":"³ÇÊз¿²ú","ÐÒ¸£ÀïAPP":"ÐÒ¸£Àï", "Öйú·¿¼ÛÐÐÇé":"Öйú·¿¼ÛÐÐÇé","³£ÖÝס·¿":"³£ÖÝס·¿"] + def esSources = ["°²¾Ó¿ÍС³ÌÐò":"°²¾Ó¿Í","ËÑ·¿":"ËÑ·¿","Öî¸ðÕÒ·¿APP":"Öî¸ðÕÒ·¿","ÐÒ¸£ÀïAPP":"ÐÒ¸£Àï","¼ªÎÝ":"¼ªÎÝ","Öйú·¿¼ÛÐÐÇé":"Öйú·¿¼ÛÐÐÇé","±´¿ÇÕÒ·¿":"±´¿ÇÕÒ·¿", + "Á´¼Ò":"Á´¼Ò","C21":"C21","³ÇÊз¿²úС³ÌÐò":"³ÇÊз¿²ú","ÀÖÓмÒ":"ÀÖÓмÒ","ÎÒ°®ÎÒ¼Ò":"ÎÒ°®ÎÒ¼Ò","ÖÐÔ­µØ²ú":"ÖÐÔ­µØ²ú","Íò©Ê¿PC¶Ë":"Íò©Ê¿", + "365ÌÔ·¿":"365ÌÔ·¿","Q·¿":"Q·¿","ÂóÌï":"ÂóÌï","³£ÖÝס·¿":"³£ÖÝס·¿"] static main(args) { runBatch(new SynchDistrictPrice(), args); diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/thirdPriceCrawl/ThirdDataToGatherBatch.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/thirdPriceCrawl/ThirdDataToGatherBatch.groovy index aaf9d6380..d1fb7dc6f 100644 --- a/projects/fangjia-script/src/main/groovy/com/fangjia/script/thirdPriceCrawl/ThirdDataToGatherBatch.groovy +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/thirdPriceCrawl/ThirdDataToGatherBatch.groovy @@ -33,7 +33,7 @@ class ThirdDataToGatherBatch extends BaseBatch{ "Á´¼Ò":"lianjia_esf","Íò©Ê¿":"tuboshi_esf","³ÇÊз¿²ú":"cityhouse_esf","±´¿ÇÕÒ·¿":"beike_esf","Q·¿":"qfang_esf","Q·¿(ÐÂ)":"qfang_new","ÖÐÔ­µØ²ú(ÐÂ)":"zhongyuan_new", "ÀÖÓмÒ":"leyoujia_esf","ÀÖÓмÒ(ÐÂ)":"leyoujia_new","·¿Ì½":"fangtan_esf","·¿¶à¶à":"fangdoudou_esf","С×ʼÒ":"xiaozijia_esf","ÎÒ°®ÎÒ¼Ò":"5i5j_esf","ÂóÌï":"maitian_esf", "·¿Í¾":"fangtoo_esf","C21":"c21_esf","ÀÖ¾Ó":"leju_esf","·¿²ú³¬ÊÐ":"fccs_esf","58ͬ³Ç":"58tc_esf","365ÌÔ·¿":"365house_esf","¼ªÎÝ":"jiwu_esf","ÐÒ¸£Àï":"xingfuli_esf", - "Öйú·¿¼ÛÐÐÇé":"creprice_esf","³£ÖÝס·¿":"zwfc_esf" + "Öйú·¿¼ÛÐÐÇé":"creprice_esf","³£ÖÝס·¿":"zwfc_esf", "·¿ÌìÏÂ":"fang_esf" ] public static ExecutorService fixedThreadPool = Executors.newFixedThreadPool(2) diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/util/BaiduMapUtils.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/util/BaiduMapUtils.groovy index cb84af2c7..9a4003b7d 100644 --- a/projects/fangjia-script/src/main/groovy/com/fangjia/script/util/BaiduMapUtils.groovy +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/util/BaiduMapUtils.groovy @@ -9,13 +9,8 @@ import net.sf.json.JSONObject class BaiduMapUtils { - private static String AK = "9E99D3540e4dafb7894f7b9fe27fa6b5"; - def static AKS = ["hj5KqPjaGA3uivtg8uS8XfAnj9X1kPMr","xjFg7DfDqvQleIZasM3ph8Zi2Lw8kgCg", - "4pb6fzrWIzvibDu8L1o8DGoY2h1wRIUq","ZzX6mRFfE5GKn4cpUp24Q3OyUIHnfQAR","79ac4ea49e7dedbf80b0ecd475d07784", - "9E99D3540e4dafb7894f7b9fe27fa6b5","W3M5uHfcrmlAdhQjf6v93LCI", "C8bb035aacf602551e829e4c64575224", - "B42b12d01f2dee712fd66c3e886158a4", "1a3cde429f38434f1811a75e1a90310c","W3M5uHfcrmlAdhQjf6v93LCI", - "C8bb035aacf602551e829e4c64575224", "B42b12d01f2dee712fd66c3e886158a4", - "1a3cde429f38434f1811a75e1a90310c","9E99D3540e4dafb7894f7b9fe27fa6b5"]; + private static String AK = "1a3cde429f38434f1811a75e1a90310c"; + def static AKS = ["1a3cde429f38434f1811a75e1a90310c","1a3cde429f38434f1811a75e1a90310c"]; public static boolean HAS_AVAILABLE_AK = true; static def getAddress(lng, lat) throws Exception{ @@ -83,8 +78,8 @@ class BaiduMapUtils { throw new RuntimeException("ÎÞ¿ÉÓðٶÈAK"); } System.out.println("¸ü»»AK"); - for(int i = 0 ;i < AKS.length; i++){ - if(i == AKS.length - 1){ + for(int i = 0 ;i < AKS.size(); i++){ + if(i == AKS.size() - 1){ AK = AKS[0]; HAS_AVAILABLE_AK = false; throw new RuntimeException("ÎÞ¿ÉÓðٶÈAK"); @@ -127,6 +122,35 @@ class BaiduMapUtils { return null } + + public static JSONObject geocoding(locationstr) { + String url = "https://api.map.baidu.com/reverse_geocoding/v3/?ak="+AK+"&output=json&coordtype=gcj02ll&location="+locationstr + boolean stop = false; + int recount = 0; + JSONObject jsonObj = null + while(!stop && recount<6) { + try{ + HttpRequest request = new HttpRequest(); + try{ + String result = request.get(url,null,"UTF-8"); + def json = JSONObject.fromObject(result); + if(json.getInt("status") >= 300){ + changeAK(); + recount++ + }else{ + jsonObj = json.result + } + }catch (Exception e){ + e.printStackTrace(); + } + }catch (Exception e){ + recount++; + println e.getMessage() + } + } + return jsonObj + } + public static def searchByBounds(key, min_lat, min_lng, max_lat, max_lng){ boolean stop = false; int recount = 0; diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/util/CommonUtils.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/util/CommonUtils.groovy index 21887e3db..ac9704830 100644 --- a/projects/fangjia-script/src/main/groovy/com/fangjia/script/util/CommonUtils.groovy +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/util/CommonUtils.groovy @@ -1,6 +1,7 @@ package com.fangjia.script.util import com.fangjia.core.RegionData +import com.fangjia.core.util.HttpRequest import com.mongodb.BasicDBObject import com.mongodb.DBCollection import com.mongodb.DBObject @@ -192,6 +193,19 @@ public class CommonUtils { } } + static void recalcAverage(String city, String region, String name, Integer count =1 , String category="sell", Boolean retainHistory=true){ + def url = "http://192.168.0.100:38080/FangJiaDataService/districtPriceCalculate"; + def params = new HashMap(); + params.city = city; + params.region = region; + params.name = name; + params.count = count.toString(); + params.category = category; + params.retainHistory = retainHistory.toString(); + HttpRequest request = new HttpRequest(); + println(request.get(url, params, "UTF-8")) + } + /** * ÖØËãÐ¡Çø¾ù¼Û * @param city @@ -221,7 +235,7 @@ public class CommonUtils { cmd.put("name", name) cmd.put('estate_type', estateType) cmd.put("calc_date", calcDate) - cmd.put("calc_type", 0) + cmd.put("calc_type", calcType) println(cmd) DBObject data = new BasicDBObject() data.put("category", "sell") diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/util/GeoHelper.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/util/GeoHelper.groovy index cb59203cf..e04562271 100644 --- a/projects/fangjia-script/src/main/groovy/com/fangjia/script/util/GeoHelper.groovy +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/util/GeoHelper.groovy @@ -1,4 +1,8 @@ package com.fangjia.script.util + + +import java.text.DecimalFormat + class GeoHelper { @@ -60,10 +64,159 @@ class GeoHelper { // return GetLatLon(a, distance, angle); // } // - public static void main(String[] args){ - GeoHelper.GetLatLon( 31.222361, 121.380462, 0.6, 0); - GetDistance(31.222361, 121.380462, 31.227757176233904, 121.380462); - } + public static haversine(lat1, lon1, lat2, lon2) { + def R = 6371; // µØÇò°ë¾¶£¨¹«À + def lat1Rad = lat1 * (Math.PI / 180); + def lat2Rad = lat2 * (Math.PI / 180); + def deltaLat = (lat2 - lat1) * (Math.PI / 180); + def deltaLon = (lon2 - lon1) * (Math.PI / 180); + + def a = Math.sin(deltaLat / 2) ** 2 + + Math.cos(lat1Rad) * Math.cos(lat2Rad) * + Math.sin(deltaLon / 2) ** 2; + + def c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); + return R * c; // ·µ»Ø¾àÀ루¹«À + } + + public static calculateArea(coords) { + def area = 0; + def n = coords.size(); + + for (def i = 0; i < n; i++) { + def j = (i + 1) % n; + area += coords[i][0] * coords[j][1]; + area -= coords[j][0] * coords[i][1]; + } + area = Math.abs(area) / 2; // ƽ·½¶È + + // ת»»ÎªÆ½·½¹«Àï + def conversionFactor = 111.32; // ´óԼÿ¶È¾­Î³¶ÈµÄ¹«ÀïÊý£¨¿¼Âǵ½µØÇòµÄÇúÂÊ£© + + def df = new DecimalFormat("#.000000") + return Double.parseDouble(df.format(area * conversionFactor * conversionFactor)) // ·µ»ØÃæ»ý£¨Æ½·½¹«À +// return area * conversionFactor * conversionFactor + } + + + public static void main(String[] args){ +// GeoHelper.GetLatLon( 31.222361, 121.380462, 0.6, 0); +// GetDistance(31.222361, 121.380462, 31.227757176233904, 121.380462); + + List> coordinates = [ + [ + 117.61878540582734, + 24.667331307258223 + ], + [ + 117.61400840589488, + 24.670008244935104 + ], + [ + 117.60936140565889, + 24.671837202755682 + ], + [ + 117.60834440585768, + 24.668667276729821 + ], + [ + 117.60696440583342, + 24.667256309201207 + ], + [ + 117.60517040553236, + 24.667762297657362 + ], + [ + 117.60272340547806, + 24.660100475272998 + ], + [ + 117.60254340555321, + 24.658630509428463 + ], + [ + 117.60206940590035, + 24.654781598282568 + ], + [ + 117.60254840557604, + 24.652731645907636 + ], + [ + 117.60346440599301, + 24.651555673447035 + ], + [ + 117.6070314057805, + 24.652578649754957 + ], + [ + 117.61605140571805, + 24.651939664372833 + ], + [ + 117.6156454058372, + 24.654165613124405 + ], + [ + 117.61559340595863, + 24.655023593107103 + ], + [ + 117.61535440558418, + 24.658990501065318 + ], + [ + 117.61662340528017, + 24.659352492642654 + ], + [ + 117.61678740531192, + 24.661365445721003 + ], + [ + 117.61472940542001, + 24.661623439403797 + ], + [ + 117.61462940586114, + 24.661837434759093 + ], + [ + 117.61470140583106, + 24.662665415879701 + ], + [ + 117.61487240553515, + 24.663165403873506 + ], + [ + 117.61522940591078, + 24.663494396452791 + ], + [ + 117.6157014059138, + 24.663523395394918 + ], + [ + 117.61627240565099, + 24.663438397829282 + ], + [ + 117.61693540544979, + 24.663181403867725 + ], + [ + 117.61878540582734, + 24.667331307258223 + ] + ] + + double area = calculateArea(coordinates) + println "The area of the polygon is: ${String.format("%.2f", area)} square kilometers" + } } diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/webCrawl/Test.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/webCrawl/Test.groovy index 796aaedcb..11d317c09 100644 --- a/projects/fangjia-script/src/main/groovy/com/fangjia/script/webCrawl/Test.groovy +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/webCrawl/Test.groovy @@ -43,15 +43,15 @@ class Test { static main(args) { // String test1 = " qwdwqd ssss "; -// String test2 = "¡¡qwdwqd ss"; +// String FiveLevelTest = "¡¡qwdwqd ss"; // String test3 = "qwdwqd¡¡£ä£ä"; // // test1 = test1.replaceAll("¡¡|\\s+", " "); -// test2 = test2.replaceAll("¡¡|\\s+", " "); +// FiveLevelTest = FiveLevelTest.replaceAll("¡¡|\\s+", " "); // test3 = test3.replaceAll("¡¡|\\s+", " "); // // String[] arrs1 = test1.split("\\s+") -// String[] arrs2 = test2.split("\\s+") +// String[] arrs2 = FiveLevelTest.split("\\s+") // String[] arrs3 = test3.split("\\s+") // // println arrs1 diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/wenyan/guojun.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/wenyan/guojun.groovy new file mode 100644 index 000000000..e837ce0ba --- /dev/null +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/wenyan/guojun.groovy @@ -0,0 +1,50 @@ +package com.fangjia.script.wenyan + +import com.fangjia.core.ProvinceData +import com.fangjia.core.RegionData +import com.fangjia.core.util.DateUtil +import com.fangjia.core.util.Mongo3Utils +import com.fangjia.script.util.CommonUtils +import com.fangjia.script.util.DbUtils +import com.fangjia.script.util.ElasticUtils +import com.fangjia.script.util.ExcelUtils +import com.mongodb.BasicDBObject +import org.bson.Document +import org.elasticsearch.action.get.GetRequest +import org.elasticsearch.action.get.GetResponse +import org.elasticsearch.client.RequestOptions +import org.elasticsearch.client.RestHighLevelClient + +////def data = [] +////data << ["ID","³ÇÊÐ","ÇøÓò","Ãû³Æ","µØÖ·", "²ÆÁ¦ÆÀ¼¶"] +//RestHighLevelClient client = ElasticUtils.getClient89("192.168.0.89") +//district_analy_data_client = Mongo3Utils.getDbCollection("fangjia_stat", "district_analy_data") +//level_map = ["1": "S", "2": "A", "3": "B", "4": "C", "5": "D"] +//level_maps = new HashMap<>() +//for(def key in level_map.keySet()){ +// level_maps.put(level_map[key], key) +//} +//ExcelUtils.modify("C:\\Users\\goojia\\Desktop\\²ÆÁ¦ÆÀ¼¶-ÏÃÃÅ.xlsx",{List item-> +//// GetResponse response = client.get(new GetRequest("community_summary", item["A"] as String), RequestOptions.DEFAULT) +//// def query = new Document("city", item['B'].toString().replace("ÊÐ", "")) +//// query.append("region", item['C'].replace("Çø", "")) +//// query.append("district_name", item["D"]) +//// def stat = district_analy_data_client.find(query).first() +//// println(query) +//// item["F"] = response.getSourceAsMap()?.consumption_rating +//// item["G"] = stat?.community_rating +// item["G"] = level_maps.get(item["G"], null) +//// println(item) +//}) +//System.exit(0) +////for (def region in ["˼Ã÷", "Ïè°²", "ºþÀï"]) { +//// DbUtils.seaweed.find(new BasicDBObject("city", "ÏÃÃÅ").append("region", region).append("cat", "district").append("status", 0)).each { BasicDBObject dbo -> +//// println("${dbo._id.toString()}\t${dbo.city}ÊÐ\t${dbo.region}Çø\t${dbo.name}\t${dbo.address}") +//// } +////} + +ExcelUtils.read("C:\\Users\\goojia\\Desktop\\º£ÄÏÊ¡³ÇÊоù¼Û.xlsx",1).each {List item-> + def yearMonth = DateUtil.formatByPattern(item[0], "yyyyMM").toInteger() + + println(item) +} \ No newline at end of file diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/wenyan/xiamen/BankBounds.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/wenyan/xiamen/BankBounds.groovy new file mode 100644 index 000000000..3c5615061 --- /dev/null +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/wenyan/xiamen/BankBounds.groovy @@ -0,0 +1,15 @@ +package com.fangjia.script.wenyan.xiamen + +import com.fangjia.core.util.DataUtil +import com.fangjia.core.util.GeoUtils +import com.fangjia.script.util.ExcelUtils + +ExcelUtils.multiThreadingModify("D:\\±¾µØ»¯²¿Êð\\ÏÃÃÅÒøÐÐÊý¾Ý\\Íøµã¾­Î³¶ÈÒµÎñÑ¡ÔñÍøµã.xlsx",{List item -> + def location = item['E'] + if(location){ + def lng = location.toString().split(",")[0].toDouble() + def lat = location.toString().split(",")[1].toDouble() + def bounds = GeoUtils.getAround(lat, lng, 3000) + item["G"] = "${DataUtil.getRound(6, bounds[2])},${DataUtil.getRound(6,bounds[0])},${DataUtil.getRound(6,bounds[3])},${DataUtil.getRound(6,bounds[1])}" + } +}) diff --git a/projects/fangjia-script/src/main/groovy/com/fangjia/script/yinjihaun/amap/GaoDeApiUtils.groovy b/projects/fangjia-script/src/main/groovy/com/fangjia/script/yinjihaun/amap/GaoDeApiUtils.groovy index 65da1a7be..60dc4ddb2 100644 --- a/projects/fangjia-script/src/main/groovy/com/fangjia/script/yinjihaun/amap/GaoDeApiUtils.groovy +++ b/projects/fangjia-script/src/main/groovy/com/fangjia/script/yinjihaun/amap/GaoDeApiUtils.groovy @@ -12,7 +12,8 @@ import org.jsoup.Jsoup import java.util.zip.GZIPInputStream class GaoDeApiUtils { - def static GAO_DE_AK = "c6fcd4bfbc40d73ee762b8115dca3390" //±¦½£ + //94c74c60e102972a8d17b7b75d7403be + def static GAO_DE_AK = "94c74c60e102972a8d17b7b75d7403be" //±¦½£:c6fcd4bfbc40d73ee762b8115dca3390 //15021384995£ºdfc2245bac8a7b2d5b62e060e59d4eca /** @@ -29,12 +30,28 @@ class GaoDeApiUtils { params.put("location", location) params.put("extensions","all") String content - try { - content = new HttpRequest().get("http://restapi.amap.com/v3/geocode/regeo", params, "utf-8") - } catch (Exception e) { - content = new HttpRequest().get("http://restapi.amap.com/v3/geocode/regeo", params, "utf-8") + def stop = true + JSONObject jsonObj = null + def errorCount = 1 + while (stop){ + try { + content = new HttpRequest().get("http://restapi.amap.com/v3/geocode/regeo", params, "utf-8") + } catch (Exception e) { + content = new HttpRequest().get("http://restapi.amap.com/v3/geocode/regeo", params, "utf-8") + } + jsonObj = JSONObject.fromObject(content) + if(jsonObj.status!="1"){ + println jsonObj + errorCount ++ + Thread.sleep(3000) + if(errorCount>3){ + stop = false + } + }else{ + stop = false + } } - JSONObject jsonObj = JSONObject.fromObject(content) + return jsonObj } diff --git a/projects/fangjia-service/src/main/java/com/fangjia/service/address/AddressParserServiceImpl.java b/projects/fangjia-service/src/main/java/com/fangjia/service/address/AddressParserServiceImpl.java index c7c6b08a6..c3b82f22c 100644 --- a/projects/fangjia-service/src/main/java/com/fangjia/service/address/AddressParserServiceImpl.java +++ b/projects/fangjia-service/src/main/java/com/fangjia/service/address/AddressParserServiceImpl.java @@ -10,6 +10,7 @@ import com.fangjia.dal.mongo.fangjia.model.ServerArea; import com.fangjia.dal.mongo.model.bkoff.HouseLoudong; import com.fangjia.dal.mongo.model.bkoff.Loudong; import com.fangjia.dal.seaweed.dao.SeaweedDao; +import com.fangjia.dal.seaweed.model.District; import com.fangjia.dal.seaweed.model.Seaweed; import com.fangjia.service.address.mode.*; import com.fangjia.service.address.processor.AddressDistrictProcessors; @@ -164,127 +165,12 @@ public class AddressParserServiceImpl implements AddressParserService { return building; } Building matchedBuilding; - //µ÷ÓÃCRFËã·¨ÇзÖÊý¾Ý - /*JSONObject jsonObj = null; - if(params.isUseCrf() && AddressParserGoal.Match.equals(addr.getAddressParserGoal())){ - jsonObj = getDataFromCRF(addr.getOrgAddress()); - if(jsonObj != null){ - String poi = (jsonObj.containsKey("community_model") ? jsonObj.getString("community_model") : "") + - (jsonObj.containsKey("poi_model") ? jsonObj.getString("poi_model") : "") + - (jsonObj.containsKey("subpoi_model") ? jsonObj.getString("subpoi_model") : ""); - if(StringUtils.isNotBlank(poi)){ - if(addr.getKeywords()==null || !addr.getKeywords().contains(poi)){ - addr.setKeywords(poi); - } - } - } - }*/ - //keywordsʹÓÃaliyun½Ó¿Ú·µ»ØµÄpoi - AliyunBo aliyunBo = null; - if(params.isUseAliyunApi() && AddressParserGoal.Match.equals(addr.getAddressParserGoal())){ - aliyunBo = aliyunService.addressStand(params.getAddress(), params.getCity()); - if(aliyunBo != null){ - String poi = ((aliyunBo.getPoi() == null ? "":aliyunBo.getPoi()) + (aliyunBo.getSubpoi() == null ? "":aliyunBo.getSubpoi())).replaceAll("\\s*", ""); - if(StringUtils.isNotBlank(poi)){ - if(addr.getKeywords()==null || !addr.getKeywords().contains(poi)){ - addr.setKeywords(poi); - } - } - if(StringUtils.isNotBlank(aliyunBo.getCity())){ - addr.setCity(RegionData.formatCity(aliyunBo.getCity())); - } - if(StringUtils.isNotBlank(addr.getKeywords()) && addr.getOrgAddress().indexOf(addr.getKeywords())>-1){ - String str = AddressParserUtil.match(Pattern.compile(".*´å(.*(×é|¶Ó))?\\d+(ºÅ)?$"), addr.getOrgAddress().substring(addr.getOrgAddress().indexOf(addr.getKeywords()),addr.getOrgAddress().length())); - if(StringUtils.isNotBlank(str)){ - String newKeywords = AddressParserUtil.match(Pattern.compile(".*´å(.*(×é|¶Ó))?"), str); - if(StringUtils.isNotBlank(newKeywords)){ - addr.setKeywords(newKeywords); - addr.setParsedPropertyName(newKeywords); - aliyunBo.setRoomno(str.replace(newKeywords,"")); - } - } - } - } - } addr.addKeyword(addr.getOrgAddress()); - if(params.isUseMap()){ - matchedBuilding = findMatchedBuilding(addr, params.getBuildingType(), MetaDataType.MAP); - }else{ - matchedBuilding = findMatchedBuilding(addr, params.getBuildingType(), MetaDataType.CPDB); - } - - /*if(jsonObj != null){ - //ÏçÕòÓÅ»¯ - String township = jsonObj.containsKey("town") ? jsonObj.getString("town") : ""; - if(StringUtils.isBlank(addr.getTownship()) && StringUtils.isNotBlank(township)){ - String town = AddressParserUtil.match(AddressParserPatterns.TOWN, township); - if(StringUtils.isNotBlank(town)){ - addr.setTownship(town); - } - } - //µÀ·ÓÅ»¯(Á½±ß¾ùÈ¥µôÏçÕò) - String street = addr.getStreet(); - String streetNumber = addr.getStreetNumber(); - String streetCrf = jsonObj.containsKey("road") ? jsonObj.getString("road") : ""; - String streetNumberCrf = jsonObj.containsKey("roadno") ? jsonObj.getString("roadno") : ""; - //È¥µô·ÃûÖк¬ÓÐÏçÕòÃûµÄ - if(StringUtils.isNotBlank(addr.getTownship())){ - street = StringUtils.isNotBlank(street) ? street.replace(addr.getTownship(),"") : street; - streetCrf = StringUtils.isNotBlank(streetCrf) ? streetCrf.replace(addr.getTownship(),"") : streetCrf; - } - - //crf½âÎö³öµÄ·ÃûΪ¿Õ¡¢ÓëJava½âÎö³ö·ÃûÒ»Ö»ò²»Âú×ãÕýÔòÔò²»´¦Àí - if(StringUtils.isNotBlank(streetCrf) && !streetCrf.equals(street) && StringUtils.isNotBlank(AddressParserUtil.match(AddressParserPatterns.STREET, streetCrf))){ - //Java½âÎö³ö·ÃûΪ¿Õ - if(StringUtils.isBlank(street)){ - street = streetCrf; - if(StringUtils.isNotBlank(streetNumberCrf)){ - streetNumber = streetNumberCrf; - } - }else{ - //CRF°üº¬java½âÎö³öµÄ·Ãû»òJava½âÎö³öµÄ·Ãû°üº¬CRF½âÎö³öµÄ·Ãû²¢ÇÒ¶àÓಿ·ÖÒ²Âú×ã·ÃûÕýÔò - if(streetCrf.contains(street) || (street.contains(streetCrf) && StringUtils.isBlank(AddressParserUtil.match(AddressParserPatterns.STREET, street.replace(streetCrf,""))))){ - street = streetCrf; - } - } - addr.setStreet(street); - addr.setStreetNumber(streetNumber); - } - //poi´¦Àí - //ûÓÐÆ¥ÅäÉÏ¿âÖÐÐ¡ÇøÊ± - if(StringUtils.isBlank(matchedBuilding.getId())){ - String poi = (jsonObj.containsKey("community") ? jsonObj.getString("community") : "") + - (jsonObj.containsKey("poi") ? jsonObj.getString("poi") : "") + - (jsonObj.containsKey("subpoi") ? jsonObj.getString("subpoi") : ""); - //È¥µô·ÃûÖк¬ÓÐÏçÕòÃûºÍ·Ãû getParsedPropertyName - if(StringUtils.isNotBlank(addr.getTownship())){ - poi = poi.replace(addr.getTownship(),""); - } - if(StringUtils.isNotBlank(addr.getStreet())){ - poi = poi.replace(addr.getStreet(),""); - } - addr.setParsedPropertyName(poi); - } - //Â¥¶°¡¢µ¥Ôª¡¢ÊҺŠ- String houseNo = (jsonObj.containsKey("houseno") ? jsonObj.getString("houseno") : "").replaceAll("[\u4E00-\u9FA5]", ""); - String cellNo = (jsonObj.containsKey("cellno") ? jsonObj.getString("cellno") : "").replaceAll("[\u4E00-\u9FA5]", ""); - String floorNo = (jsonObj.containsKey("floorno") ? jsonObj.getString("floorno") : "").replaceAll("[\u4E00-\u9FA5]", ""); - String roomNo = (jsonObj.containsKey("roomno") ? jsonObj.getString("roomno") : "").replaceAll("[\u4E00-\u9FA5]", ""); - addr.setOrgBuildingNumber(houseNo); - addr.setBuildingNumber(houseNo); - addr.setOrgUnitNumber(cellNo); - addr.setUnitNumber(cellNo); - addr.setFloor(floorNo); - addr.setOrgRoomNumber(roomNo); - addr.setRoomNumber(roomNo); - }*/ + matchedBuilding = findMatchedBuilding(addr, params.getBuildingType(), MetaDataType.CPDB); matchedBuilding.setProvince(addr.getProvince()); matchedBuilding.setSearchAddress(addr); matchedBuilding.setSuggestName(getSuggestName(matchedBuilding)); matchedBuilding.setSuggestAddress(getSuggestAddress(matchedBuilding)); - if(params.isUseAliyunApi() && aliyunBo != null && AddressParserGoal.Match.equals(addr.getAddressParserGoal())){ - completBuildingField(matchedBuilding, aliyunBo, params); - } Address tempAddr = matchedBuilding.getSearchAddress(); if((StringUtils.isBlank(tempAddr.getStreet()) || StringUtils.isBlank(tempAddr.getStreetNumber())) && AddressParserGoal.Match.equals(addr.getAddressParserGoal())){ AddressMatchMetaData meta = getMapMeta(addr); @@ -436,8 +322,27 @@ public class AddressParserServiceImpl implements AddressParserService { AddressScoreResult scoreResult = findMatchedMetaData(addr, buildingType, metaDataType); if(scoreResult.getResult().size() > 0){ AddressMatchMetaData matchedMate = scoreResult.getResult().get(0); + + if(matchedMate.getMetaDataType() == MetaDataType.CPDB){ - return new Building(districtService.findById(matchedMate.getId(), MATCH_PROPERTY_FIELDS), scoreResult.getScore(matchedMate)); + District district = districtService.findById(matchedMate.getId(), MATCH_PROPERTY_FIELDS); + if("1".equals(addr.getPropertyType())){ + if(!district.getEstateType2().equals("±ðÊû") || !district.getName().endsWith("±ðÊû")){ + District districtNew = districtService.findDistrict(new DistrictKey(district.getCity(), district.getRegion(), district.getName() + "±ðÊû"), district.getCategory()); + if(districtNew != null){ + district = districtNew; + } + } + + }else if("2".equals(addr.getPropertyType())){ + if(!district.getEstateType2().equals("ÉÌס") || !district.getName().endsWith("ÉÌס¥")){ + District districtNew = districtService.findDistrict(new DistrictKey(district.getCity(), district.getRegion(), district.getName() + "ÉÌס¥"), district.getCategory()); + if(districtNew != null){ + district = districtNew; + } + } + } + return new Building(districtService.findById(district.getId(), MATCH_PROPERTY_FIELDS), scoreResult.getScore(matchedMate)); }else{ return new Building(matchedMate, scoreResult.getScore(matchedMate)); } @@ -500,6 +405,7 @@ public class AddressParserServiceImpl implements AddressParserService { addr.setProvince(params.getProvince()); addr.setDebugName(params.getDebugName()); addr.setUseMap(params.isUseMap()); + addr.setPropertyType(params.getPropertyType()); return AddressProcessors.process(addr); } diff --git a/projects/fangjia-service/src/main/java/com/fangjia/service/address/mode/Address.java b/projects/fangjia-service/src/main/java/com/fangjia/service/address/mode/Address.java index 02cee4b25..d7cb876aa 100644 --- a/projects/fangjia-service/src/main/java/com/fangjia/service/address/mode/Address.java +++ b/projects/fangjia-service/src/main/java/com/fangjia/service/address/mode/Address.java @@ -15,6 +15,7 @@ import java.util.*; */ public class Address { + private String propertyType; private String province; private String city; private String district; @@ -769,6 +770,14 @@ public class Address { this.geoRegion = geoRegion; } + public String getPropertyType() { + return propertyType; + } + + public void setPropertyType(String propertyType) { + this.propertyType = propertyType; + } + @Override public String toString() { return "Address{" + diff --git a/projects/fangjia-service/src/main/java/com/fangjia/service/address/mode/MatchParams.java b/projects/fangjia-service/src/main/java/com/fangjia/service/address/mode/MatchParams.java index e53c9701f..bcff0e11b 100644 --- a/projects/fangjia-service/src/main/java/com/fangjia/service/address/mode/MatchParams.java +++ b/projects/fangjia-service/src/main/java/com/fangjia/service/address/mode/MatchParams.java @@ -14,7 +14,7 @@ public class MatchParams { private String suggestName; /**µ÷ÊÔʱ¶ÏµãÐ¡ÇøÃû*/ private String debugName; - + private String propertyType; /**Óû§ÊäÈëµØÖ·*/ private String address; /**½¨ÖþÀàÐͽâÎö³ö¶ÔÓ¦µÄ½¨ÖþÎï*/ @@ -135,4 +135,12 @@ public class MatchParams { public void setDebugName(String debugName) { this.debugName = debugName; } + + public String getPropertyType() { + return propertyType; + } + + public void setPropertyType(String propertyType) { + this.propertyType = propertyType; + } } diff --git a/projects/fangjia-service/src/main/java/com/fangjia/service/address/processor/GeoProcessor.java b/projects/fangjia-service/src/main/java/com/fangjia/service/address/processor/GeoProcessor.java index bb33d7dbd..90b572a2d 100644 --- a/projects/fangjia-service/src/main/java/com/fangjia/service/address/processor/GeoProcessor.java +++ b/projects/fangjia-service/src/main/java/com/fangjia/service/address/processor/GeoProcessor.java @@ -19,7 +19,7 @@ import java.util.Map; */ public class GeoProcessor extends AbstractAddressProcessor { - private static final String KEY = "4ccfe3c898a9489884bd2bcb1ef6dcde"; + private static final String KEY = "94d4f0e7d11745e84419a68104c06315"; private static final Logger logger = Logger.getLogger(GeoProcessor.class); List POI_LEVELS = Arrays.asList("´åׯ", "ÈȵãÉÌȦ", "ÐËȤµã", "ÃÅÅÆºÅ", "µ¥ÔªºÅ", "µÀ·½»²æÂ·¿Ú", "ÃÅÅÆºÅ"); @@ -31,10 +31,7 @@ public class GeoProcessor extends AbstractAddressProcessor { if(!address.isUseMap()){ return RepeatStatus.NEXT; } - String addr = address.getEffectiveAddress(); - if(addr == null || addr.length() < 3){ - addr = address.getOrgAddress(); - } + String addr = address.getOrgAddress(); HttpRequest request = new HttpRequest(); Map params = new HashMap(); params.put("address", addr); @@ -46,8 +43,17 @@ public class GeoProcessor extends AbstractAddressProcessor { logger.info("¸ßµÂAPI:" + response.toString()); if (response.getInt("status") == 1) { JSONArray geocodes = response.getJSONArray("geocodes"); + JSONObject json = null; if(geocodes.size() > 0){ - JSONObject json = geocodes.getJSONObject(0); + for(int i=0; i < geocodes.size(); i++){ + if(POI_LEVELS.contains(geocodes.getJSONObject(i).getString("level"))){ + json = geocodes.getJSONObject(i); + break; + } + } + if(json == null){ + return RepeatStatus.NEXT; + } if(json.get("district") instanceof String){ String city = address.getCity(); if(city == null){ @@ -66,15 +72,15 @@ public class GeoProcessor extends AbstractAddressProcessor { String location = json.getString("location"); address.setLng(Double.valueOf(location.split(",")[0])); address.setLat(Double.valueOf(location.split(",")[1])); - String tmp = "{ \"_source\": [\"seaweed_id\"], \"query\": {\"geo_shape\": {\"shape\": {\"shape\": {\"type\": \"Point\",\"coordinates\":[location]},\"relation\": \"CONTAINS\"}}}}"; + String tmp = "{ \"_source\": [\"comm_id\"], \"query\": {\"geo_shape\": {\"shape\": {\"shape\": {\"type\": \"Point\",\"coordinates\":[location]},\"relation\": \"CONTAINS\"}}}}"; tmp = tmp.replace("location", location); Map headers = new HashMap(); headers.put("Authorization","Basic ZGV2ZWxvcGVyOjVlOGVkZDg1MWQyZmRmYmQ3NDE1MjMyYzY3MzY3Y2Mz"); - JSONObject resp = JSONObject.fromObject(request.postWithBody("http://192.168.0.206:9200/seaweed_polygon/_search", JSONObject.fromObject(tmp),headers,"UTF-8")); + JSONObject resp = JSONObject.fromObject(request.postWithBody("http://192.168.0.89:9200/seaweed_fence/_search", JSONObject.fromObject(tmp),headers,"UTF-8")); if(resp.containsKey("hits") && resp.getJSONObject("hits").containsKey("hits")){ JSONArray hits = resp.getJSONObject("hits").getJSONArray("hits"); if(hits.size() > 0){ - String seaweedId = hits.getJSONObject(0).getJSONObject("_source").getString("seaweed_id"); + String seaweedId = hits.getJSONObject(0).getJSONObject("_source").getString("comm_id"); address.setPolygonSeaweedId(seaweedId); } } diff --git a/projects/fangjia-service/src/main/java/com/fangjia/service/api/AutoCompleteBo.java b/projects/fangjia-service/src/main/java/com/fangjia/service/api/AutoCompleteBo.java index 0b886ac78..9e714a4bb 100644 --- a/projects/fangjia-service/src/main/java/com/fangjia/service/api/AutoCompleteBo.java +++ b/projects/fangjia-service/src/main/java/com/fangjia/service/api/AutoCompleteBo.java @@ -2,6 +2,8 @@ package com.fangjia.service.api; import com.fangjia.dal.mongo.model.PriceJiucuo; +import java.util.List; + public class AutoCompleteBo { private String val; private String desc; @@ -20,6 +22,8 @@ public class AutoCompleteBo { private Double lat; private Double lng; + private String alias; + /*** @Deprecated end ****/ public String getName() { @@ -133,4 +137,12 @@ public class AutoCompleteBo { public void setLng(Double lng) { this.lng = lng; } + + public String getAlias() { + return alias; + } + + public void setAlias(String alias) { + this.alias = alias; + } } diff --git a/projects/fangjia-service/src/main/java/com/fangjia/service/datastore/CzbankSampleService.java b/projects/fangjia-service/src/main/java/com/fangjia/service/datastore/CzbankSampleService.java index 4de80fa46..2e648b498 100644 --- a/projects/fangjia-service/src/main/java/com/fangjia/service/datastore/CzbankSampleService.java +++ b/projects/fangjia-service/src/main/java/com/fangjia/service/datastore/CzbankSampleService.java @@ -38,4 +38,13 @@ public interface CzbankSampleService { * @return */ List findSample2(List queryBeans, int max); + + /** + * ±±½»Ëù·¿Ô´²éѯ + * + * @param queryBeans + * @param max + * @return + */ + List findSampleForBse(List queryBeans, int max); } diff --git a/projects/fangjia-service/src/main/java/com/fangjia/service/datastore/CzbankSampleServiceImpl.java b/projects/fangjia-service/src/main/java/com/fangjia/service/datastore/CzbankSampleServiceImpl.java index 99fc3ce39..f6177cfca 100644 --- a/projects/fangjia-service/src/main/java/com/fangjia/service/datastore/CzbankSampleServiceImpl.java +++ b/projects/fangjia-service/src/main/java/com/fangjia/service/datastore/CzbankSampleServiceImpl.java @@ -31,6 +31,7 @@ import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.TermQuery; import org.apache.solr.client.solrj.util.ClientUtils; +import java.math.BigDecimal; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -90,6 +91,26 @@ public class CzbankSampleServiceImpl implements CzbankSampleService { return collateralList; } + /** + * ±±½»Ëù·¿Ô´²éѯ + * + * @param queryBeans + * @param max + * @return + */ + @Override + public List findSampleForBse(List queryBeans, int max) { + List collateralList = new ArrayList(); + for (CollateralSampleQueryBean queryBean : queryBeans) { + if (queryBean.getProperty() != null) { + Collateral collateral = findSampleByQueryForBse(queryBean, max); + if (null != collateral) { + collateralList.add(collateral); + } + } + } + return collateralList; + } @Override public List findShopSample(ShopCollateralSampleQueryBean queryBean, int max) { @@ -229,7 +250,7 @@ public class CzbankSampleServiceImpl implements CzbankSampleService { } } - List samples = findJnbankSampleByDistrict(district, keys, names, queryBean.getPropertyTypeCode(), queryBean.getUpdateDate(), districtStat); + List samples = findJnbankSampleByDistrict(district, keys, names, queryBean.getPropertyTypeCode(), queryBean.getUpdateDate(), districtStat, target.getStrctureArea()); // scoreForSample(samples, target); sortForSample(samples, target); @@ -269,7 +290,7 @@ public class CzbankSampleServiceImpl implements CzbankSampleService { } } - List nearlySample = findJnbankSampleByDistrict(district, arroundKeys, arroundNnames, queryBean.getPropertyTypeCode(), queryBean.getUpdateDate(), districtStat); + List nearlySample = findJnbankSampleByDistrict(district, arroundKeys, arroundNnames, queryBean.getPropertyTypeCode(), queryBean.getUpdateDate(), districtStat, target.getStrctureArea()); for (SampleWrapper sample : nearlySample) { sample.setProperty(district); @@ -346,13 +367,13 @@ public class CzbankSampleServiceImpl implements CzbankSampleService { propertyLife = "40"; } else { if (sample.getBuildStructureCode() != null) { - if ("10".equals(sample.getBuildStructureCode())) { + if ("10".equals(sample.getBuildStructureCode().toString())) { propertyLife = "70"; - } else if ("20".equals(sample.getBuildStructureCode())) { + } else if ("20".equals(sample.getBuildStructureCode().toString())) { propertyLife = "60"; - } else if ("40".equals(sample.getBuildStructureCode())) { + } else if ("40".equals(sample.getBuildStructureCode().toString())) { propertyLife = "40"; - } else if ("30".equals(sample.getBuildStructureCode())) { + } else if ("30".equals(sample.getBuildStructureCode().toString())) { propertyLife = "50"; } else { propertyLife = "60"; @@ -600,6 +621,127 @@ public class CzbankSampleServiceImpl implements CzbankSampleService { return collateral; } + /** + * ±±½»Ëù·çÏÕ»ºÊÍ + * + * @param queryBean + * @param max + * @return + */ + private Collateral findSampleByQueryForBse(CollateralSampleQueryBean queryBean, int max) { + + SampleWrapper target = convertQueryBean2Sample(queryBean); + District district = queryBean.getProperty(); + DistrictStat districtStat = districtStatService.findOneDistrictStatsSort(district.getCity(), district.getRegion(), district.getName(), new Date()); + if (districtStat == null) { + districtStat = districtStatService.findOneDistrictStatsSort(district.getCity(), district.getRegion(), district.getName(), DateUtil.add(new Date(), -7)); + } + List keys = new ArrayList(); + List querySamples = new ArrayList(); + String key = district.getName() + "_" + district.getRegion() + "_" + district.getCity(); + // ÐÞ¸Ä + keys.add(key); + if (district.getAlias() != null) { + for (String alia : district.getAlias()) { + if (StringUtils.isNotBlank(alia)) { + key = alia + "_" + district.getRegion() + "_" + district.getCity(); + if (!keys.contains(key)) { + keys.add(key); + } + } + } + } + List samples = findBeijiaoShouSampleByDistrict(keys, district.getEstateType2(), queryBean.getPropertyTypeCode(), queryBean.getUpdateDate(), districtStat, target.getStrctureArea(), 20); + keys.clear(); + sortForSample(samples, target); + SampleWrapper maxSample = null; + SampleWrapper minSample = null; + + querySamples.addAll(samples); + if (querySamples.size() < max + 10) { + // ²éѯ³É½»²¹³ä TODO + List dealPriceQuery = new ArrayList(); + dealPriceQuery.add(new QueryParam("city", district.getCity())); + dealPriceQuery.add(new QueryParam("region", district.getRegion())); + List names = new ArrayList(); + names.add(district.getName()); + if (district.getAlias() != null) { + for (String alias : district.getAlias()) { + if (StringUtils.isNotBlank(alias) && alias.length() >= 4) { + names.add(alias); + } + } + } + dealPriceQuery.add(new QueryParam("districtName", QueryParam.IN_OPERATOR, names)); + dealPriceQuery.add(new QueryParam("tradeDate", QueryParam.GREATER_THAN_OPERATOR, DateUtil.add(new Date(), Calendar.MONTH, -12))); + List dealPriceSortParams = new ArrayList(); + dealPriceSortParams.add(new SortParam("tradeDate", false)); + List dealPrices = dealPriceDao.findAllByParams(dealPriceQuery, dealPriceSortParams, 0, 10, DEAL_PRICE_FIELDS); + for (DealPrice dealPrice : dealPrices) { + SampleWrapper sample = convertDealPrice2Sample(dealPrice); + if (isAvailableSample(sample)) { + // ¹ýÂ˼۸ñ²îÒì·Ç³£´óµÄ³É½» + if (districtStat != null && districtStat.getAvg_price_2b() != null && (districtStat.getAvg_price_2b() <= sample.getUnitPrice() * 1.3) + && (districtStat.getAvg_price_2b() >= sample.getUnitPrice() * 0.7)) { + querySamples.add(sample); + } + } + } + } + for (SampleWrapper sample : querySamples) { + sample.setProperty(queryBean.getProperty()); + if (maxSample == null) { + maxSample = sample; + } else { + if (sample.getUnitPrice() > maxSample.getUnitPrice()) { + maxSample = sample; + } + } + + if (minSample == null) { + minSample = sample; + } else { + if (sample.getUnitPrice() < minSample.getUnitPrice()) { + minSample = sample; + } + } + } + + List selectedSample = new ArrayList(max); + Set priceUniqueKeys = new HashSet(); + for (int i = 0; i < querySamples.size() && selectedSample.size() < max; i++) { + SampleWrapper wrapper = querySamples.get(i); + if (priceUniqueKeys.contains(wrapper.getUnitPrice())) { + continue; + } + priceUniqueKeys.add(wrapper.getUnitPrice()); + selectedSample.add(querySamples.get(i)); + } + fillOthersSimpleInfo(selectedSample); + List sampleList = new ArrayList(selectedSample.size()); + + for (SampleWrapper sampleWrapper : selectedSample) { + Sample sample = new Sample(); + BeanUtils.copyProperties(sampleWrapper, sample); + sampleList.add(sample); + } + + + Collateral collateral = new Collateral(); + collateral.setCltNo(queryBean.getCltNo()); + collateral.setSample(sampleList); + + if (minSample != null) { + collateral.setMinPrice(minSample.getUnitPrice()); + } + + if (maxSample != null) { + collateral.setMaxPrice(maxSample.getUnitPrice()); + } + + return collateral; + } + /** * ´´½¨Ò»¸ö±ê×¼Ñù±¾ @@ -770,7 +912,6 @@ public class CzbankSampleServiceImpl implements CzbankSampleService { return d1.compareTo(d2); } }); - List prices = new ArrayList(); for (SampleWrapper sample : samples) { if (!prices.contains(sample.getUnitPrice())) { @@ -989,7 +1130,7 @@ public class CzbankSampleServiceImpl implements CzbankSampleService { * @param startDate * @return */ - private List findJnbankSampleByDistrict(District district, List keys, List names, String estateType, Date startDate, DistrictStat districtStat) { + private List findJnbankSampleByDistrict(District district, List keys, List names, String estateType, Date startDate, DistrictStat districtStat,double area) { BooleanQuery nameQuery = new BooleanQuery(); @@ -1013,8 +1154,10 @@ public class CzbankSampleServiceImpl implements CzbankSampleService { houseQuery.add(new QueryParam("avgPrice", QueryParam.GREATER_THAN_EQUAL_OPERATOR, (int) (avgPrice * 0.5)));//0.85 houseQuery.add(new QueryParam("avgPrice", QueryParam.LESS_THAN_EQUAL_OPERATOR, (int) (avgPrice * 1.5)));//1.15 } + houseQuery.add(new QueryParam("area", QueryParam.LESS_THAN_EQUAL_OPERATOR, area + 30)); + houseQuery.add(new QueryParam("area", QueryParam.GREATER_THAN_EQUAL_OPERATOR, area - 30)); - if (nameQuery.clauses().size() == 0) { + if (nameQuery.clauses().isEmpty()){ return samples; } BooleanQuery srQuery = new BooleanQuery(); @@ -1290,6 +1433,13 @@ public class CzbankSampleServiceImpl implements CzbankSampleService { // sample.setCity(fangjiaOfficialAreaMap.getCityCode()); // sample.setDistrict(fangjiaOfficialAreaMap.getDistrictCode()); // } + } + // ¸ù¾Ý2BÓë¾ù¼ÛµÄϵÊý½øÐÐÅÐ¶Ï + for (SampleWrapper sample : samples) { + if (districtStat != null && districtStat.getAvg_price_2b() != null) { + sample.setUnitPrice((int) (sample.getUnitPrice() * (districtStat.getAvg_price_2b() * 1.00 / districtStat.getAvgPrice()))); + } + } return samples; } diff --git a/projects/fangjia-service/src/main/java/com/fangjia/service/datastore/DistrictService.java b/projects/fangjia-service/src/main/java/com/fangjia/service/datastore/DistrictService.java index 04e5d5de2..e00652926 100644 --- a/projects/fangjia-service/src/main/java/com/fangjia/service/datastore/DistrictService.java +++ b/projects/fangjia-service/src/main/java/com/fangjia/service/datastore/DistrictService.java @@ -466,6 +466,8 @@ public interface DistrictService extends ModeService { */ public List findByKey(String city, String region, String name, String cat); + public List findAllByNameAndCat(String city, String region, String name, String cat); + /** * ²éÕÒÖܱß×îÏàËÆµÄÂ¥ÅÌ * diff --git a/projects/fangjia-service/src/main/java/com/fangjia/service/datastore/DistrictServiceImpl.java b/projects/fangjia-service/src/main/java/com/fangjia/service/datastore/DistrictServiceImpl.java index dd625b469..9628214e5 100644 --- a/projects/fangjia-service/src/main/java/com/fangjia/service/datastore/DistrictServiceImpl.java +++ b/projects/fangjia-service/src/main/java/com/fangjia/service/datastore/DistrictServiceImpl.java @@ -992,7 +992,7 @@ public class DistrictServiceImpl implements DistrictService { /** * ¸ù¾ÝQueryBean²éѯ·ûºÏÌõ¼þµÄÐ¡ÇøÊýÁ¿ - * + * * @param districtQueryBean * @return */ @@ -1067,7 +1067,7 @@ public class DistrictServiceImpl implements DistrictService { } /** - * + * * @param keyList * List * @param isNewDistrict @@ -1098,7 +1098,7 @@ public class DistrictServiceImpl implements DistrictService { */ /** - * + * * @param districtKey * DistrictKey * @param isNewDistrict @@ -1171,7 +1171,7 @@ public class DistrictServiceImpl implements DistrictService { /** * ²éÕÒÐ¡Çø - * + * * @return */ private District doFindDistrict(DistrictKey key, String cat) { @@ -1203,7 +1203,7 @@ public class DistrictServiceImpl implements DistrictService { /** * ²éÕÒÐ¡Çø - * + * * @param key * DistrictKey * @param isNewDistrict @@ -1252,7 +1252,7 @@ public class DistrictServiceImpl implements DistrictService { /* * (non-Javadoc) - * + * * @see com.fangjia.service.datastore.DistrictService#processDistrictInfo(java * .util.List, java.lang.String) */ @@ -1535,15 +1535,23 @@ public class DistrictServiceImpl implements DistrictService { List ret = new ArrayList(); for (District d : districts) { - if (null == d.getLat2() || null == d.getLng2()) { + if (d.getLat2() == null || d.getLng2() == null) { continue; } double dis = GeoUtils.calculateDistance(lng, lat, d.getLng() / 10000000000.0, d.getLat() / 10000000000.0); if (dis <= radius) { + d.setScore(dis); // Assuming District has a `distance` field to store the calculated distance. ret.add(d); } } + + Collections.sort(ret, new Comparator() { + @Override + public int compare(District d1, District d2) { + return Double.compare(d1.getScore(), d2.getScore()); + } + }); return ret; } @@ -2003,6 +2011,9 @@ public class DistrictServiceImpl implements DistrictService { if (!RegionData.isCity(city)) { city = RegionData.formatCity(city); } + if (city == null){ + return null; + } District districtInfo = findDistrict(new DistrictKey(city, region, name), target); // ÏȾ«È·²éѯ£¬²é²»µ½ÔÙ¸ù¾Ý±ðÃûÆ¥Åä if (districtInfo != null) { @@ -2191,6 +2202,20 @@ public class DistrictServiceImpl implements DistrictService { return districtDao.findAllByParams(params); } + @Override + public List findAllByNameAndCat(String city, String region, String name, String cat) { + List params = new ArrayList(5); + params.add(new QueryParam("city", city)); + if (StringUtils.isNotBlank(region)) { + params.add(new QueryParam("region", region)); + } + if (StringUtils.isNotBlank(name)) { + params.add(new QueryParam("name", name)); + } + params.add(new QueryParam("category", cat)); + return districtDao.findAllByParams(params); + } + @Override public District findOneByKey(DistrictKey districtKey, String cat) { List districts = findByKey(districtKey.getCity(), districtKey.getRegion(), districtKey.getName(), @@ -2204,13 +2229,13 @@ public class DistrictServiceImpl implements DistrictService { /** * ²éÕÒÖܱß×îÏàËÆµÄÂ¥ÅÌ - * + * *

     	 * ÏàËÆÌõ¼þ
     	 * |½¨ÖþÀàÐÍ(estate_type2)Ïàͬ»ò°üº¬
     	 * |½¨ÖþÄê´ú×î¶à²î5Äê
     	 * 
    - * + * * @param district * @param radiusMeters * @param limit @@ -2283,6 +2308,9 @@ public class DistrictServiceImpl implements DistrictService { @SuppressWarnings("unchecked") public List findNearestDistrict(District district, int radiusMeters, int limit) { + if (district == null) { + return Collections.emptyList(); + } String cacheKey = district.getCity() + "#" + district.getRegion() + "#" + district.getName() + "#" + radiusMeters + "#" + limit; Object obj = CacheUtils.getValue(this.getClass(), cacheKey); if (obj != null) { @@ -2406,7 +2434,7 @@ public class DistrictServiceImpl implements DistrictService { /** * ²éÕÒ×î½üµÄÂ¥ÅÌ - * + * * @param district * @param radiusMeters * @param limit diff --git a/projects/fangjia-service/src/main/java/com/fangjia/service/datastore/EvaluationServiceImpl.java b/projects/fangjia-service/src/main/java/com/fangjia/service/datastore/EvaluationServiceImpl.java index ac396fe4b..070094dc1 100644 --- a/projects/fangjia-service/src/main/java/com/fangjia/service/datastore/EvaluationServiceImpl.java +++ b/projects/fangjia-service/src/main/java/com/fangjia/service/datastore/EvaluationServiceImpl.java @@ -1079,6 +1079,10 @@ public class EvaluationServiceImpl implements EvaluationService { if (evaluation != null && evaluation.getAvgPrice2b() != null && evaluation.getAvgPrice2b() > 0) { avgPrice = evaluation.getAvgPrice2b().intValue(); } + // ¿ÉÄÜ´æÔÚevaluation.getAvgPrice2bΪ¿ÕÇé¿ö + if (stat.getAvgPrice2b() > 0) { + avgPrice = stat.getAvgPrice2b(); + } } } diff --git a/projects/fangjia-service/src/main/java/com/fangjia/service/datastore/HouseService.java b/projects/fangjia-service/src/main/java/com/fangjia/service/datastore/HouseService.java index 1e35fc1e1..1b112e38c 100644 --- a/projects/fangjia-service/src/main/java/com/fangjia/service/datastore/HouseService.java +++ b/projects/fangjia-service/src/main/java/com/fangjia/service/datastore/HouseService.java @@ -7,6 +7,7 @@ import java.util.Map; import com.fangjia.dal.FacetQuery; import com.fangjia.dal.common.DistrictKey; +import com.fangjia.dal.datastore.model.RentHouse; import com.fangjia.datastore.driver.FacetResult; import com.fangjia.service.bo.HousePDSBo; import com.fangjia.service.bo.HouseScorer; @@ -469,4 +470,8 @@ public interface HouseService extends ModeService { long findHouseByYearMonth(String city, String region, String districtName, int yearMonth); HashMap findHouseStat(District districtKey, Integer avgPrice); + + List findNearestHasHouseByLocation(String city, Double lat, Double lng, String cat, int radiusMeters, int limit); + + } diff --git a/projects/fangjia-service/src/main/java/com/fangjia/service/datastore/HouseServiceImpl.java b/projects/fangjia-service/src/main/java/com/fangjia/service/datastore/HouseServiceImpl.java index 3093de0a2..5eb20dfea 100644 --- a/projects/fangjia-service/src/main/java/com/fangjia/service/datastore/HouseServiceImpl.java +++ b/projects/fangjia-service/src/main/java/com/fangjia/service/datastore/HouseServiceImpl.java @@ -8,6 +8,7 @@ import com.fangjia.dal.common.FangjiaServerAreaContextHolder; import com.fangjia.dal.common.ServerAreaData; import com.fangjia.dal.datastore.dao.HouseDao; import com.fangjia.dal.datastore.model.House; +import com.fangjia.dal.datastore.model.RentHouse; import com.fangjia.dal.mongo.dao.UserHouseDao; import com.fangjia.dal.mongo.fangjia.model.ServerArea; import com.fangjia.dal.mongo.model.UserHouse; @@ -2613,4 +2614,25 @@ public class HouseServiceImpl implements HouseService { return value; } + @Override + public List findNearestHasHouseByLocation(String city, Double lat, Double lng, String cat, int radiusMeters, int limit) { + if (lat == null || lng == null || lat <= 0 ||lng <= 0) { + return Collections.EMPTY_LIST; + } + List params = new ArrayList(); + params.add(new QueryParam("cat", cat)); + if (StringUtils.isNotBlank(city)){ + params.add(new QueryParam("city", city)); + } + SdQuery sdQuery = new SdQuery(); + sdQuery.setPoint(lat + "," + lng); + sdQuery.setField("lat_lng"); + sdQuery.setDistance(String.valueOf((double) radiusMeters / 1000.0)); +// sdQuery.setDistance(String.valueOf(radiusMeters)); + params.add(new QueryParam(QueryParam.SD_PARAM_NAME, sdQuery)); + List sortParams = Arrays.asList(new SortParam("latLng", true)); + List list = houseDao.findAllByParams(params, null, 0, limit); + return list; + } + } diff --git a/projects/fangjia-service/src/main/java/com/fangjia/service/datastore/RentHouseService.java b/projects/fangjia-service/src/main/java/com/fangjia/service/datastore/RentHouseService.java index e12108154..1bdd09d3c 100644 --- a/projects/fangjia-service/src/main/java/com/fangjia/service/datastore/RentHouseService.java +++ b/projects/fangjia-service/src/main/java/com/fangjia/service/datastore/RentHouseService.java @@ -3,6 +3,7 @@ package com.fangjia.service.datastore; import java.util.List; import java.util.Map; +import com.fangjia.dal.datastore.model.House; import org.sothis.core.util.Pager; import com.fangjia.dal.FacetQueryResult; @@ -208,4 +209,6 @@ public interface RentHouseService extends ModeService { boolean refreshHouse(String houseId, int userId); // Óû§ÖÐÐÄ·¢²¼·¿Ô´½Ó¿Ú END + + List findNearestHasHouseByLocation(String city, Double lat, Double lng, String cat, int radiusMeters, int limit); } diff --git a/projects/fangjia-service/src/main/java/com/fangjia/service/datastore/RentHouseServiceImpl.java b/projects/fangjia-service/src/main/java/com/fangjia/service/datastore/RentHouseServiceImpl.java index 647f14f8d..7cfdba6f9 100644 --- a/projects/fangjia-service/src/main/java/com/fangjia/service/datastore/RentHouseServiceImpl.java +++ b/projects/fangjia-service/src/main/java/com/fangjia/service/datastore/RentHouseServiceImpl.java @@ -1,14 +1,10 @@ package com.fangjia.service.datastore; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; +import com.fangjia.dal.*; +import com.fangjia.dal.datastore.dao.HouseDao; +import com.fangjia.dal.datastore.model.House; import org.apache.commons.lang.StringUtils; import org.apache.lucene.search.Query; import org.sothis.core.util.CollectionUtils; @@ -16,11 +12,6 @@ import org.sothis.core.util.Pager; import com.fangjia.core.util.DateUtil; import com.fangjia.core.util.RandomUtil; -import com.fangjia.dal.FacetQuery; -import com.fangjia.dal.FacetQueryResult; -import com.fangjia.dal.QueryParam; -import com.fangjia.dal.SortParam; -import com.fangjia.dal.SrQuery; import com.fangjia.dal.common.DistrictKey; import com.fangjia.dal.common.FangjiaServerAreaContextHolder; import com.fangjia.dal.common.ServerAreaData; @@ -70,6 +61,8 @@ public class RentHouseServiceImpl implements RentHouseService { private UserHouseDao userHouseDao; private MetroDistanceService metroDistanceService; + private HouseDao houseDao; + public FacetQueryResult randomGainHouse(RentHouseQueryBean queryBean, int count) { long totalCount = this.findHouseCount(queryBean); int endCount = count * 100; @@ -831,6 +824,27 @@ public class RentHouseServiceImpl implements RentHouseService { return true; } + @Override + public List findNearestHasHouseByLocation(String city,Double lat, Double lng, String cat,int radiusMeters, int limit) { + if (lat == null || lng == null || lat <= 0 ||lng <= 0) { + return Collections.EMPTY_LIST; + } + List params = new ArrayList(); + params.add(new QueryParam("cat", cat)); + if (StringUtils.isNotBlank(city)){ + params.add(new QueryParam("city", city)); + } + SdQuery sdQuery = new SdQuery(); + sdQuery.setPoint(lat + "," + lng); + sdQuery.setField("lat_lng"); + sdQuery.setDistance(String.valueOf((double) radiusMeters / 1000.0)); +// sdQuery.setDistance(String.valueOf(radiusMeters)); + params.add(new QueryParam(QueryParam.SD_PARAM_NAME, sdQuery)); + List sortParams = Arrays.asList(new SortParam("latLng", true)); + List list = rentHouseDao.findAllByParams(params, null, 0, limit); + return list; + } + public boolean refreshHouse(String houseId, int userId,String source) { List params = new ArrayList(2); params.add(new QueryParam("userId", userId)); @@ -899,4 +913,7 @@ public class RentHouseServiceImpl implements RentHouseService { this.metroDistanceService = metroDistanceService; } + public void setHouseDao(HouseDao houseDao) { + this.houseDao = houseDao; + } } diff --git a/projects/fangjia-service/src/main/java/com/fangjia/service/datastore/SeaweedService.java b/projects/fangjia-service/src/main/java/com/fangjia/service/datastore/SeaweedService.java new file mode 100644 index 000000000..ea250dfc9 --- /dev/null +++ b/projects/fangjia-service/src/main/java/com/fangjia/service/datastore/SeaweedService.java @@ -0,0 +1,13 @@ +package com.fangjia.service.datastore; + +import com.fangjia.dal.QueryParam; +import com.fangjia.dal.common.DistrictKey; +import com.fangjia.dal.seaweed.model.Seaweed; +import com.fangjia.dal.seaweed.model.Shop; + +import java.util.List; + +public interface SeaweedService { + List findSeaweedByLocation(double lat, double lng, double radius,String cat,int limit); + List findSeaweedByLocation(double lat, double lng, double radius,String cat); +} diff --git a/projects/fangjia-service/src/main/java/com/fangjia/service/datastore/SeaweedServiceImpl.java b/projects/fangjia-service/src/main/java/com/fangjia/service/datastore/SeaweedServiceImpl.java new file mode 100644 index 000000000..e054a7663 --- /dev/null +++ b/projects/fangjia-service/src/main/java/com/fangjia/service/datastore/SeaweedServiceImpl.java @@ -0,0 +1,102 @@ +package com.fangjia.service.datastore; + +import com.fangjia.core.util.CacheUtils; +import com.fangjia.core.util.CacheUtils.CachePolicyEnum; +import com.fangjia.core.util.GeoUtils; +import com.fangjia.dal.QueryParam; +import com.fangjia.dal.common.DistrictKey; +import com.fangjia.dal.seaweed.dao.SeaweedDao; +import com.fangjia.dal.seaweed.dao.ShopDao; +import com.fangjia.dal.seaweed.model.District; +import com.fangjia.dal.seaweed.model.Seaweed; +import com.fangjia.dal.seaweed.model.Shop; +import com.fangjia.service.index.BoostQueryPolicy; +import org.apache.commons.lang.StringUtils; +import org.sothis.core.util.Closure; +import org.sothis.core.util.CollectionUtils; + +import java.util.*; + +public class SeaweedServiceImpl implements SeaweedService { + private SeaweedDao seaweedDao; + + @Override + public List findSeaweedByLocation(double lat, double lng, double radius,String cat,int limit) { + double[] latlngs = GeoUtils.getAround(lat, lng, radius); + List params = new ArrayList(); + params.add(new QueryParam("category", cat)); + params.add(new QueryParam("status", 0)); + params.add(new QueryParam("lat", QueryParam.GREATER_THAN_EQUAL_OPERATOR, latlngs[0] * 10000000000d)); + params.add(new QueryParam("lat", QueryParam.LESS_THAN_EQUAL_OPERATOR, latlngs[1] * 10000000000d)); + params.add(new QueryParam("lng", QueryParam.GREATER_THAN_EQUAL_OPERATOR, latlngs[2] * 10000000000d)); + params.add(new QueryParam("lng", QueryParam.LESS_THAN_EQUAL_OPERATOR, latlngs[3] * 10000000000d)); + + List seaweeds = seaweedDao.findAllByParams(params,limit); + if (CollectionUtils.isEmpty(seaweeds)) { + return Collections.emptyList(); + } + + List ret = new ArrayList(); + for (Seaweed d : seaweeds) { + if (d.getLat() == null || d.getLng() == null) { + continue; + } + + double dis = GeoUtils.calculateDistance(lng, lat, d.getLng() / 10000000000.0, d.getLat() / 10000000000.0); + if (dis <= radius) { + d.setScore(dis); // Assuming District has a `distance` field to store the calculated distance. + ret.add(d); + } + } + + Collections.sort(ret, new Comparator() { + @Override + public int compare(Seaweed d1, Seaweed d2) { + return Double.compare(d1.getScore(), d2.getScore()); + } + }); + return ret; + } + + @Override + public List findSeaweedByLocation(double lat, double lng, double radius, String cat) { + double[] latlngs = GeoUtils.getAround(lat, lng, radius); + List params = new ArrayList(); + params.add(new QueryParam("category", cat)); + params.add(new QueryParam("status", 0)); + params.add(new QueryParam("lat", QueryParam.GREATER_THAN_EQUAL_OPERATOR, latlngs[0] * 10000000000d)); + params.add(new QueryParam("lat", QueryParam.LESS_THAN_EQUAL_OPERATOR, latlngs[1] * 10000000000d)); + params.add(new QueryParam("lng", QueryParam.GREATER_THAN_EQUAL_OPERATOR, latlngs[2] * 10000000000d)); + params.add(new QueryParam("lng", QueryParam.LESS_THAN_EQUAL_OPERATOR, latlngs[3] * 10000000000d)); + + List seaweeds = seaweedDao.findAllByParams(params); + if (CollectionUtils.isEmpty(seaweeds)) { + return Collections.emptyList(); + } + + List ret = new ArrayList(); + for (Seaweed d : seaweeds) { + if (d.getLat() == null || d.getLng() == null) { + continue; + } + + double dis = GeoUtils.calculateDistance(lng, lat, d.getLng() / 10000000000.0, d.getLat() / 10000000000.0); + if (dis <= radius) { + d.setScore(dis); // Assuming District has a `distance` field to store the calculated distance. + ret.add(d); + } + } + + Collections.sort(ret, new Comparator() { + @Override + public int compare(Seaweed d1, Seaweed d2) { + return Double.compare(d1.getScore(), d2.getScore()); + } + }); + return ret; + } + + public void setSeaweedDao(SeaweedDao seaweedDao) { + this.seaweedDao = seaweedDao; + } +} diff --git a/projects/fangjia-service/src/main/java/com/fangjia/service/district/DistrictStatService.java b/projects/fangjia-service/src/main/java/com/fangjia/service/district/DistrictStatService.java index a308e1a67..623a779b0 100644 --- a/projects/fangjia-service/src/main/java/com/fangjia/service/district/DistrictStatService.java +++ b/projects/fangjia-service/src/main/java/com/fangjia/service/district/DistrictStatService.java @@ -295,6 +295,17 @@ public interface DistrictStatService { * @return */ public int findLatestDistrictAvgPrice(DistrictKey districtKey,Date weekend); + + /** + * »ñµÃÖ¸¶¨Ê±¼äµÄÐ¡Çø¾ù¼Û2B + * + * @param districtKey + * @param weekend + * @return + */ + int findLatestDistrictAvgPrice2B(DistrictKey districtKey,Date weekend); + + /** diff --git a/projects/fangjia-service/src/main/java/com/fangjia/service/district/DistrictStatServiceImpl.java b/projects/fangjia-service/src/main/java/com/fangjia/service/district/DistrictStatServiceImpl.java index 242aac83e..9d2259bd7 100644 --- a/projects/fangjia-service/src/main/java/com/fangjia/service/district/DistrictStatServiceImpl.java +++ b/projects/fangjia-service/src/main/java/com/fangjia/service/district/DistrictStatServiceImpl.java @@ -1524,6 +1524,52 @@ public class DistrictStatServiceImpl implements DistrictStatService { return value; } + @Override + public int findLatestDistrictAvgPrice2B(DistrictKey districtKey, Date weekend) { + if (weekend == null) { + weekend = DateUtil.getFirstDayOfWeek(new Date()); + } + String cacheKey = districtKey.getCity() + "_" + districtKey.getRegion() + "_" + districtKey.getName() + "_2B_" + DateUtil.formatToYYMMDD(weekend); + Object obj = CacheUtils.getValue(this.getClass(), cacheKey); + if (obj != null) { + return (Integer)obj; + } + Integer value = doFindLatestDistrictAvgPrice2B(districtKey, weekend); + CacheUtils.putValue(CachePolicyEnum.LONG, this.getClass(), cacheKey, value); + return value; + } + + public Integer doFindLatestDistrictAvgPrice2B(DistrictKey districtKey, Date weekend){ + + DistrictStatBo statBo = districtStatService.findDistrictStat(districtKey); + if (statBo != null && statBo.getDefaultDistrictStat() != null) { + if (statBo.getDefaultDistrictStat().getAvg_price_2b() > 0) { + return statBo.getDefaultDistrictStat().getAvg_price_2b(); + } + if (statBo.getDefaultDistrictStat().getAvgPrice() > 0) { + return statBo.getDefaultDistrictStat().getAvgPrice(); + } + } + + double r = AveragerUtil.getFloatingRate(districtKey, weekend); + if (StringUtils.isNotBlank(districtKey.getCity()) && StringUtils.isNotBlank(districtKey.getRegion())) { + RegionStat regionStat = regionStatService.findRegionStat(districtKey.getCity(), districtKey.getRegion(), null); + if (regionStat != null) { + return (int) (regionStat.getAvgPrice() * r); + } + } + + if (StringUtils.isNotBlank(districtKey.getCity())) { + RegionStat regionStat = regionStatService.findRegionStat(districtKey.getCity(), null, null); + if (regionStat != null) { + return (int) (regionStat.getAvgPrice() * r); + } + } + + return 0; + + } + public Integer doFindLatestDistrictAvgPrice(DistrictKey districtKey, Date weekend){ DistrictStatBo statBo = districtStatService.findDistrictStat(districtKey); diff --git a/projects/fangjia-service/src/main/java/com/fangjia/service/index/SellTriggerServiceImpl.java b/projects/fangjia-service/src/main/java/com/fangjia/service/index/SellTriggerServiceImpl.java index 1f7ab6869..501865bc5 100644 --- a/projects/fangjia-service/src/main/java/com/fangjia/service/index/SellTriggerServiceImpl.java +++ b/projects/fangjia-service/src/main/java/com/fangjia/service/index/SellTriggerServiceImpl.java @@ -206,23 +206,23 @@ public class SellTriggerServiceImpl implements TriggerService { newObj.put("floor_range", getFloorRange(object)); -// if (null != district) { -// if (district.getLat() != null && district.getLng() != null && district.getLat() > 0 && district.getLng() > 0) { -// try { -// newObj.put("lat", district.getLat()); -// newObj.put("lng", district.getLng()); -// double lat = (district.getLat() / 10000000000.0); -// double lng = (district.getLng() / 10000000000.0); -// if (lat >= -90 && lat <= 90 && lng >= -180 && lng <= 180) { -// newObj.put("lat_lng", lat + "," + lng); -// } -// } catch (NumberFormatException e) { -// if (LOGGER.isErrorEnabled()) { -// LOGGER.error("error pase lat(" + district.getLat() + ") or lng("+ district.getLng() + "): ", e); -// } -// } -// } -// } + if (null != district) { + if (district.getLat() != null && district.getLng() != null && district.getLat() > 0 && district.getLng() > 0) { + try { + newObj.put("lat", district.getLat()); + newObj.put("lng", district.getLng()); + double lat = (district.getLat() / 10000000000.0); + double lng = (district.getLng() / 10000000000.0); + if (lat >= -90 && lat <= 90 && lng >= -180 && lng <= 180) { + newObj.put("lat_lng", lat + "," + lng); + } + } catch (NumberFormatException e) { + if (LOGGER.isErrorEnabled()) { + LOGGER.error("error pase lat(" + district.getLat() + ") or lng("+ district.getLng() + "): ", e); + } + } + } + } ReasonStatus status = sellDataFilter.apply(object, inputDate); if (isVisible(status)) { diff --git a/projects/fangjia-service/src/main/java/com/fangjia/service/mongo/fangjia/ApiCountLogService.java b/projects/fangjia-service/src/main/java/com/fangjia/service/mongo/fangjia/ApiCountLogService.java new file mode 100644 index 000000000..a664bb95c --- /dev/null +++ b/projects/fangjia-service/src/main/java/com/fangjia/service/mongo/fangjia/ApiCountLogService.java @@ -0,0 +1,17 @@ +package com.fangjia.service.mongo.fangjia; + +import com.fangjia.dal.mongo.model.ApiCountLog; +import com.fangjia.dal.mongo.model.DevelopmentZone; +import org.sothis.core.util.Pager; + +import java.util.List; +import java.util.Map; + +/** + * Created by dxy on 2015/6/8. + */ +public interface ApiCountLogService { + void save(ApiCountLog apiCountLog); + + List findApiCountLog(Long userId,String uri,Pager pager); +} diff --git a/projects/fangjia-service/src/main/java/com/fangjia/service/mongo/fangjia/ApiCountLogServiceImpl.java b/projects/fangjia-service/src/main/java/com/fangjia/service/mongo/fangjia/ApiCountLogServiceImpl.java new file mode 100644 index 000000000..e5822841e --- /dev/null +++ b/projects/fangjia-service/src/main/java/com/fangjia/service/mongo/fangjia/ApiCountLogServiceImpl.java @@ -0,0 +1,45 @@ +package com.fangjia.service.mongo.fangjia; + +import com.fangjia.dal.QueryParam; +import com.fangjia.dal.SortParam; +import com.fangjia.dal.mongo.dao.AdministrativeMappingDao; +import com.fangjia.dal.mongo.dao.ApiCountLogDao; +import com.fangjia.dal.mongo.dao.DevelopmentZoneDao; +import com.fangjia.dal.mongo.model.AdministrativeMapping; +import com.fangjia.dal.mongo.model.ApiCountLog; +import com.fangjia.dal.mongo.model.DevelopmentZone; +import org.apache.commons.lang.StringUtils; +import org.sothis.core.util.Pager; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.regex.Pattern; + +public class ApiCountLogServiceImpl implements ApiCountLogService { + private ApiCountLogDao apiCountLogDao; + + @Override + public void save(ApiCountLog apiCountLog) { + apiCountLogDao.save(apiCountLog); + } + + @Override + public List findApiCountLog(Long userId, String uri,Pager pager) { + List params = new ArrayList(); + if (userId!= null) { + params.add(new QueryParam("userId", userId)); + } + if (StringUtils.isNotBlank(uri)) { + Pattern pattern = Pattern.compile(".*" + uri + ".*"); + params.add(new QueryParam("uri", pattern)); + } + List sortParam = Arrays.asList(new SortParam("operateTime", false)); + return apiCountLogDao.findAllByParams(params,sortParam, pager.getStartRow(), pager.getPageSize()); + } + + public void setApiCountLogDao(ApiCountLogDao apiCountLogDao) { + this.apiCountLogDao = apiCountLogDao; + } +} diff --git a/projects/fangjia-service/src/main/java/com/fangjia/service/mongo/fangjia/DevelopmentZoneService.java b/projects/fangjia-service/src/main/java/com/fangjia/service/mongo/fangjia/DevelopmentZoneService.java index 93785c053..4094aa813 100644 --- a/projects/fangjia-service/src/main/java/com/fangjia/service/mongo/fangjia/DevelopmentZoneService.java +++ b/projects/fangjia-service/src/main/java/com/fangjia/service/mongo/fangjia/DevelopmentZoneService.java @@ -51,9 +51,9 @@ public interface DevelopmentZoneService { * @param pager * @return */ - public List findDevelopmentZone(String province,String name,String level, Pager pager); + public List findDevelopmentZone(String province,String city,String name,String level,String operateResult, Pager pager); - public long countDev(String province,String name,String level); + public long countDev(String province,String city ,String name,String level,String operateResult); public List findProvinces(); public List findCities(String province); diff --git a/projects/fangjia-service/src/main/java/com/fangjia/service/mongo/fangjia/DevelopmentZoneServiceImpl.java b/projects/fangjia-service/src/main/java/com/fangjia/service/mongo/fangjia/DevelopmentZoneServiceImpl.java index 9cc5ef376..37b698920 100644 --- a/projects/fangjia-service/src/main/java/com/fangjia/service/mongo/fangjia/DevelopmentZoneServiceImpl.java +++ b/projects/fangjia-service/src/main/java/com/fangjia/service/mongo/fangjia/DevelopmentZoneServiceImpl.java @@ -30,8 +30,8 @@ public class DevelopmentZoneServiceImpl implements DevelopmentZoneService { } @Override - public void updateDevelopmentZone(Map map,String id) { - developmentZoneDao.updateById(map,id); + public void updateDevelopmentZone(Map map, String id) { + developmentZoneDao.updateById(map, id); } @Override @@ -41,12 +41,16 @@ public class DevelopmentZoneServiceImpl implements DevelopmentZoneService { @Override - public List findDevelopmentZone(String province,String name,String level, Pager pager) { + public List findDevelopmentZone(String province, String city, String name, String level, String operateResult, Pager pager) { List params = new ArrayList(); if (StringUtils.isNotBlank(province)) { Pattern pattern = Pattern.compile(".*" + province + ".*"); params.add(new QueryParam("province", pattern)); } + if (StringUtils.isNotBlank(city)) { + Pattern pattern = Pattern.compile(".*" + city + ".*"); + params.add(new QueryParam("cityName1", pattern)); + } if (StringUtils.isNotBlank(name)) { Pattern pattern = Pattern.compile(".*" + name + ".*"); @@ -56,17 +60,28 @@ public class DevelopmentZoneServiceImpl implements DevelopmentZoneService { Pattern pattern = Pattern.compile(".*" + level + ".*"); params.add(new QueryParam("level", pattern)); } + if (StringUtils.isNotBlank(operateResult)) { + Pattern pattern = Pattern.compile(".*" + operateResult + ".*"); + params.add(new QueryParam("operateResult", pattern)); + } else { + // Èç¹û operateResult Ϊ¿Õ»òÖ»°üº¬¿Õ°××Ö·û£¬ÔòÌí¼Ó operateResult Ϊ¿ÕµÄÌõ¼þ + params.add(new QueryParam("operateResult", null)); // »òÕßʹÓÃÊʺϵÄÖµ±íʾ "Ϊ¿Õ" + } return developmentZoneDao.findAllByParams(params, pager.getStartRow(), pager.getPageSize()); } @Override - public long countDev(String province, String name,String level) { + public long countDev(String province, String city, String name, String level, String operateResult) { List params = new ArrayList(); if (StringUtils.isNotBlank(province)) { Pattern pattern = Pattern.compile(".*" + province + ".*"); params.add(new QueryParam("province", pattern)); } + if (StringUtils.isNotBlank(city)) { + Pattern pattern = Pattern.compile(".*" + city + ".*"); + params.add(new QueryParam("cityName1", pattern)); + } if (StringUtils.isNotBlank(name)) { Pattern pattern = Pattern.compile(".*" + name + ".*"); @@ -76,6 +91,13 @@ public class DevelopmentZoneServiceImpl implements DevelopmentZoneService { Pattern pattern = Pattern.compile(".*" + level + ".*"); params.add(new QueryParam("level", pattern)); } + if (StringUtils.isNotBlank(operateResult)) { + Pattern pattern = Pattern.compile(".*" + operateResult + ".*"); + params.add(new QueryParam("operateResult", pattern)); + } else { + // Èç¹û operateResult Ϊ¿Õ»òÖ»°üº¬¿Õ°××Ö·û£¬ÔòÌí¼Ó operateResult Ϊ¿ÕµÄÌõ¼þ + params.add(new QueryParam("operateResult", null)); // »òÕßʹÓÃÊʺϵÄÖµ±íʾ "Ϊ¿Õ" + } return developmentZoneDao.findCountByParams(params); } @@ -83,7 +105,7 @@ public class DevelopmentZoneServiceImpl implements DevelopmentZoneService { public List findProvinces() { List queryParams = new ArrayList(); queryParams.add(new QueryParam("type", "Ê¡·Ý")); - List allProvince = administrativeMappingDao.findAllByParams(queryParams,null,0,100,new String[]{"province"}); + List allProvince = administrativeMappingDao.findAllByParams(queryParams, null, 0, 100, new String[]{"province"}); List provinces = new ArrayList(); for (AdministrativeMapping mapping : allProvince) { provinces.add(mapping.getProvince()); @@ -96,7 +118,7 @@ public class DevelopmentZoneServiceImpl implements DevelopmentZoneService { List queryParams = new ArrayList(); queryParams.add(new QueryParam("type", "³ÇÊÐ")); queryParams.add(new QueryParam("province", province)); - List allCity = administrativeMappingDao.findAllByParams(queryParams,null,0,1000,new String[]{"city"}); + List allCity = administrativeMappingDao.findAllByParams(queryParams, null, 0, 1000, new String[]{"city"}); List cities = new ArrayList(); for (AdministrativeMapping mapping : allCity) { cities.add(mapping.getCity()); @@ -109,7 +131,7 @@ public class DevelopmentZoneServiceImpl implements DevelopmentZoneService { List queryParams = new ArrayList(); queryParams.add(new QueryParam("type", "ÇøÓò")); queryParams.add(new QueryParam("city", city)); - List allDistrict = administrativeMappingDao.findAllByParams(queryParams,null,0,1000,new String[]{"district"}); + List allDistrict = administrativeMappingDao.findAllByParams(queryParams, null, 0, 1000, new String[]{"district"}); List districts = new ArrayList(); for (AdministrativeMapping mapping : allDistrict) { districts.add(mapping.getDistrict()); diff --git a/projects/fangjia-service/src/main/java/com/fangjia/service/mongo/fangjia/PropertyStatsIndexService.java b/projects/fangjia-service/src/main/java/com/fangjia/service/mongo/fangjia/PropertyStatsIndexService.java new file mode 100644 index 000000000..e4399d1bc --- /dev/null +++ b/projects/fangjia-service/src/main/java/com/fangjia/service/mongo/fangjia/PropertyStatsIndexService.java @@ -0,0 +1,12 @@ +package com.fangjia.service.mongo.fangjia; + +import com.fangjia.dal.mongo.model.PropertyStatsIndex; +import com.fangjia.dal.mongo.model.StatsIndex; + +import java.util.List; + +public interface PropertyStatsIndexService { + + PropertyStatsIndex findById(String id); + PropertyStatsIndex findStatsIndex(String city, String district, String name, Integer yearmonth); +} diff --git a/projects/fangjia-service/src/main/java/com/fangjia/service/mongo/fangjia/PropertyStatsIndexServiceImpl.java b/projects/fangjia-service/src/main/java/com/fangjia/service/mongo/fangjia/PropertyStatsIndexServiceImpl.java new file mode 100644 index 000000000..ea742168d --- /dev/null +++ b/projects/fangjia-service/src/main/java/com/fangjia/service/mongo/fangjia/PropertyStatsIndexServiceImpl.java @@ -0,0 +1,45 @@ +package com.fangjia.service.mongo.fangjia; + +import com.fangjia.dal.QueryParam; +import com.fangjia.dal.SortParam; +import com.fangjia.dal.mongo.dao.PropertyStatsIndexDao; +import com.fangjia.dal.mongo.dao.StatsIndexDao; +import com.fangjia.dal.mongo.model.PropertyStatsIndex; +import com.fangjia.dal.mongo.model.StatsIndex; +import org.apache.commons.lang.StringUtils; + +import java.util.ArrayList; +import java.util.List; + +public class PropertyStatsIndexServiceImpl implements PropertyStatsIndexService { + private PropertyStatsIndexDao propertyStatsIndexDao; + + @Override + public PropertyStatsIndex findById(String id) { + return propertyStatsIndexDao.findById(id); + } + + @Override + public PropertyStatsIndex findStatsIndex(String city, String district, String name, Integer yearmonth) { + List params = new ArrayList(); + if (StringUtils.isNotBlank(city)) { + params.add(new QueryParam("city", city)); + } + if (StringUtils.isNotBlank(district)) { + params.add(new QueryParam("district", district)); + } + if (StringUtils.isNotBlank(name)) { + params.add(new QueryParam("name", name)); + } + if (null != yearmonth) { + params.add(new QueryParam("yearmonth", yearmonth)); + } + List sortParams = new ArrayList(); + sortParams.add(new SortParam("yearmonth", false)); + return propertyStatsIndexDao.findFirstByParams(params, sortParams); + } + + public void setPropertyStatsIndexDao(PropertyStatsIndexDao propertyStatsIndexDao) { + this.propertyStatsIndexDao = propertyStatsIndexDao; + } +} diff --git a/projects/fangjia-service/src/main/java/com/fangjia/service/mongo/fangjia/SeaweedImagesService.java b/projects/fangjia-service/src/main/java/com/fangjia/service/mongo/fangjia/SeaweedImagesService.java new file mode 100644 index 000000000..ae7dd522d --- /dev/null +++ b/projects/fangjia-service/src/main/java/com/fangjia/service/mongo/fangjia/SeaweedImagesService.java @@ -0,0 +1,19 @@ +package com.fangjia.service.mongo.fangjia; + +import com.fangjia.dal.mongo.model.DevelopmentZone; +import com.fangjia.dal.mongo.model.SeaweedImages; +import org.sothis.core.util.Pager; + +import java.util.List; +import java.util.Map; + +/** + * Created by dxy on 2015/6/8. + */ +public interface SeaweedImagesService { + public SeaweedImages findById(String id); + + public void deleteImage(String id, String url,String picType,String roomType); + public void addImage(String id, List urls,String picType,String roomType); + +} diff --git a/projects/fangjia-service/src/main/java/com/fangjia/service/mongo/fangjia/SeaweedImagesServiceImpl.java b/projects/fangjia-service/src/main/java/com/fangjia/service/mongo/fangjia/SeaweedImagesServiceImpl.java new file mode 100644 index 000000000..e738c4d3b --- /dev/null +++ b/projects/fangjia-service/src/main/java/com/fangjia/service/mongo/fangjia/SeaweedImagesServiceImpl.java @@ -0,0 +1,70 @@ +package com.fangjia.service.mongo.fangjia; + +import com.fangjia.dal.mongo.dao.SeaweedImagesDao; +import com.fangjia.dal.mongo.model.SeaweedImages; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class SeaweedImagesServiceImpl implements SeaweedImagesService { + private SeaweedImagesDao seaweedImagesDao; + + @Override + public SeaweedImages findById(String id) { + return seaweedImagesDao.findById(id); + } + + @Override + public void deleteImage(String id, String url, String picType, String roomType) { + SeaweedImages seaweedImages = seaweedImagesDao.findById(id); + if ("floorplanPics".equals(picType)) { + Map> floorplanPics = seaweedImages.getFloorplanPics(); + List roomPicList = floorplanPics.get(roomType); + if (roomPicList!=null && !roomPicList.isEmpty()){ + roomPicList.remove(url); + floorplanPics.put(roomType,roomPicList); + seaweedImages.setFloorplanPics(floorplanPics); + } + } else if ("outPics".equals(picType)) { + List outPics = seaweedImages.getOutPics(); + if (outPics != null && !outPics.isEmpty()) { + outPics.remove(url); + seaweedImages.setOutPics(outPics); + } + } + seaweedImagesDao.update(seaweedImages); + } + + @Override + public void addImage(String id, List urls, String picType, String roomType) { + SeaweedImages seaweedImages = seaweedImagesDao.findById(id); + if ("floorplanPics".equals(picType)) { + Map> floorplanPics = seaweedImages.getFloorplanPics(); + if (floorplanPics==null){ + floorplanPics = new HashMap>(); + } + List roomPicList = floorplanPics.get(roomType); + if (roomPicList!=null && !roomPicList.isEmpty()){ + roomPicList.addAll(urls); + floorplanPics.put(roomType,roomPicList); + }else { + floorplanPics.put(roomType,urls); + } + seaweedImages.setFloorplanPics(floorplanPics); + } else if ("outPics".equals(picType)) { + List outPics = seaweedImages.getOutPics(); + if (outPics != null && !outPics.isEmpty()) { + outPics.addAll(urls); + seaweedImages.setOutPics(outPics); + }else { + seaweedImages.setOutPics(urls); + } + } + seaweedImagesDao.update(seaweedImages); + } + + public void setSeaweedImagesDao(SeaweedImagesDao seaweedImagesDao) { + this.seaweedImagesDao = seaweedImagesDao; + } +} diff --git a/projects/fangjia-service/src/main/java/com/fangjia/service/mongo/fangjia/StatsIndexService.java b/projects/fangjia-service/src/main/java/com/fangjia/service/mongo/fangjia/StatsIndexService.java index 2e048b298..55c6bfc7e 100644 --- a/projects/fangjia-service/src/main/java/com/fangjia/service/mongo/fangjia/StatsIndexService.java +++ b/projects/fangjia-service/src/main/java/com/fangjia/service/mongo/fangjia/StatsIndexService.java @@ -8,17 +8,19 @@ public interface StatsIndexService { StatsIndex findById(String id); - StatsIndex findByName(String city, String yearmonth); + StatsIndex findByName(String city, Integer yearmonth); - List findAllStats(String city, String yearmonth, boolean order,String cat); - - int findAllStatsCount(String city, String name,String cat); + List findAllStats(String city, Integer yearmonth, boolean order,String cat); +// List findAllStats(String city, String district,String type, String yearmonth, boolean order,String cat); + + int findAllStatsCount(String city, Integer yearmonth,String cat); void deleteById(String id); - StatsIndex findLatestStstsIndex(String city, String yearmonth,String cat); - - public List findAllStatsNocat(String yearmonth,String cat,String source) ; + StatsIndex findLatestStstsIndex(String city, Integer yearmonth,String cat); + StatsIndex findStatsIndex(String city,String district,String type,String name, Integer yearmonth,String cat); + + public List findAllStatsNocat(Integer yearmonth,String cat,String source) ; Integer findEarliestMonth(String city, String cat, String source); diff --git a/projects/fangjia-service/src/main/java/com/fangjia/service/mongo/fangjia/StatsIndexServiceImpl.java b/projects/fangjia-service/src/main/java/com/fangjia/service/mongo/fangjia/StatsIndexServiceImpl.java index 7cb8ee88a..915e63544 100644 --- a/projects/fangjia-service/src/main/java/com/fangjia/service/mongo/fangjia/StatsIndexServiceImpl.java +++ b/projects/fangjia-service/src/main/java/com/fangjia/service/mongo/fangjia/StatsIndexServiceImpl.java @@ -20,152 +20,176 @@ import com.fangjia.service.cnAnalyzer.CnTokenizer; import com.fangjia.service.datastore.DistrictService; public class StatsIndexServiceImpl implements StatsIndexService { - private StatsIndexDao statsIndexDao; + private StatsIndexDao statsIndexDao; - @Override - public StatsIndex findById(String id) { - return statsIndexDao.findById(id); - } + @Override + public StatsIndex findById(String id) { + return statsIndexDao.findById(id); + } - @Override - public StatsIndex findByName(String city, String yearmonth) { - List params = new ArrayList(1); - if (StringUtils.isNotEmpty(city)) { - params.add(new QueryParam("city", city)); - } - if (StringUtils.isNotEmpty(city)) { - params.add(new QueryParam("yearmonth", yearmonth)); - } - List allNearbys = statsIndexDao.findAllByParams(params, - null, 0, Integer.MAX_VALUE); - return allNearbys.get(0); - } + @Override + public StatsIndex findByName(String city, Integer yearmonth) { + List params = new ArrayList(1); + if (StringUtils.isNotEmpty(city)) { + params.add(new QueryParam("city", city)); + } + if (null != yearmonth) { + params.add(new QueryParam("yearmonth", yearmonth)); + } + List allNearbys = statsIndexDao.findAllByParams(params, + null, 0, Integer.MAX_VALUE); + return allNearbys.get(0); + } - @Override - public List findAllStats(String city, String yearmonth, - boolean order, String cat) { - List params = new ArrayList(); - if (StringUtils.isNotBlank(city)) { - params.add(new QueryParam("city", city)); - } - if (StringUtils.isNotBlank(yearmonth)) { - params.add(new QueryParam("yearmonth", yearmonth)); - } - if (("ÉÌÆÌ").equals(cat)) { - params.add(new QueryParam("cat", "shop")); - } else if (("д×ÖÂ¥").equals(cat)) { - params.add(new QueryParam("cat", "office")); - } else { - params.add(new QueryParam("cat", "district")); - } - List sortParams = new ArrayList(2); - sortParams.add(new SortParam("yearmonth", order)); - sortParams.add(new SortParam("cDate", order)); - List allNearbys = statsIndexDao.findAllByParams(params,sortParams); - return allNearbys; - } + @Override + public List findAllStats(String city, Integer yearmonth, boolean order, String cat) { + List params = new ArrayList(); + if (StringUtils.isNotBlank(city)) { + params.add(new QueryParam("city", city)); + } + if (null != yearmonth) { + params.add(new QueryParam("yearmonth", yearmonth)); + } + if (("ÉÌÆÌ").equals(cat)) { + params.add(new QueryParam("cat", "shop")); + } else if (("д×ÖÂ¥").equals(cat)) { + params.add(new QueryParam("cat", "office")); + } else { + params.add(new QueryParam("cat", "district")); + } + List sortParams = new ArrayList(2); + sortParams.add(new SortParam("yearmonth", order)); + sortParams.add(new SortParam("cDate", order)); + List allNearbys = statsIndexDao.findAllByParams(params, sortParams); + return allNearbys; + } - private List createQueryParam(String city, String yearmonth) { - List params = new ArrayList(); - if (StringUtils.isNotBlank(city)) { - params.add(new QueryParam("city", city)); - } - if (StringUtils.isNotBlank(yearmonth)) { - params.add(new QueryParam("yearmonth", yearmonth)); - } - return params; - } + private List createQueryParam(String city, Integer yearmonth) { + List params = new ArrayList(); + if (StringUtils.isNotBlank(city)) { + params.add(new QueryParam("city", city)); + } + if (null != yearmonth) { + params.add(new QueryParam("yearmonth", yearmonth)); + } + return params; + } - @Override - public int findAllStatsCount(String city, String yearmonth, String cat) { - List params = new ArrayList(); - if (StringUtils.isNotBlank(city)) { - params.add(new QueryParam("city", city)); - } - if (StringUtils.isNotBlank(yearmonth)) { - params.add(new QueryParam("yearmonth", yearmonth)); - } - if (StringUtils.isNotBlank(cat)) { - params.add(new QueryParam("cat", cat)); - } else { - params.add(new QueryParam("cat", "district")); - } - List allNearbys = statsIndexDao.findAllByParams(params); - if (allNearbys.size() == 0) { - allNearbys = statsIndexDao.findAllByParams(createQueryParam(city, - yearmonth)); - } - return allNearbys.size(); - } + @Override + public int findAllStatsCount(String city, Integer yearmonth, String cat) { + List params = new ArrayList(); + if (StringUtils.isNotBlank(city)) { + params.add(new QueryParam("city", city)); + } + if (null != yearmonth) { + params.add(new QueryParam("yearmonth", yearmonth)); + } + if (StringUtils.isNotBlank(cat)) { + params.add(new QueryParam("cat", cat)); + } else { + params.add(new QueryParam("cat", "district")); + } + List allNearbys = statsIndexDao.findAllByParams(params); + if (allNearbys.size() == 0) { + allNearbys = statsIndexDao.findAllByParams(createQueryParam(city, + yearmonth)); + } + return allNearbys.size(); + } - @Override - public void deleteById(String id) { - statsIndexDao.deleteById(id); - } + @Override + public void deleteById(String id) { + statsIndexDao.deleteById(id); + } - public void setStatsIndexDao(StatsIndexDao statsIndexDao) { - this.statsIndexDao = statsIndexDao; - } + public void setStatsIndexDao(StatsIndexDao statsIndexDao) { + this.statsIndexDao = statsIndexDao; + } - @Override - public StatsIndex findLatestStstsIndex(String city, String yearmonth, String cat) { - List params = new ArrayList(); - if (StringUtils.isNotBlank(city)) { - params.add(new QueryParam("city", city)); - } - if (StringUtils.isNotBlank(yearmonth)) { - params.add(new QueryParam("yearmonth", yearmonth)); - } - if(StringUtils.isNotBlank(cat)){ - params.add(new QueryParam("cat", cat)); - } - List sortParams = new ArrayList(); - sortParams.add(new SortParam("yearmonth", false)); - return statsIndexDao.findFirstByParams(params, sortParams); - } + @Override + public StatsIndex findLatestStstsIndex(String city, Integer yearmonth, String cat) { + List params = new ArrayList(); + if (StringUtils.isNotBlank(city)) { + params.add(new QueryParam("city", city)); + } + if (null != yearmonth) { + params.add(new QueryParam("yearmonth", yearmonth)); + } + if (StringUtils.isNotBlank(cat)) { + params.add(new QueryParam("cat", cat)); + } + List sortParams = new ArrayList(); + sortParams.add(new SortParam("yearmonth", false)); + return statsIndexDao.findFirstByParams(params, sortParams); + } + + @Override + public StatsIndex findStatsIndex(String city, String district, String type, String name, Integer yearmonth, String cat) { + List params = new ArrayList(); + if (StringUtils.isNotBlank(city)) { + params.add(new QueryParam("city", city)); + } + if (StringUtils.isNotBlank(district)) { + params.add(new QueryParam("district", district)); + } + if (StringUtils.isNotBlank(type)) { + params.add(new QueryParam("type", type)); + } + if (null != yearmonth) { + params.add(new QueryParam("yearmonth", yearmonth)); + } + if (("ÉÌÆÌ").equals(cat)) { + params.add(new QueryParam("cat", "shop")); + } else if (("д×ÖÂ¥").equals(cat)) { + params.add(new QueryParam("cat", "office")); + } else { + params.add(new QueryParam("cat", "district")); + } + List sortParams = new ArrayList(); + sortParams.add(new SortParam("yearmonth", false)); + return statsIndexDao.findFirstByParams(params, sortParams); + } + @Override + public List findAllStatsNocat(Integer yearmonth, String cat, String source) { + List params = new ArrayList(); + if (null != yearmonth) { + params.add(new QueryParam("yearmonth", yearmonth)); + } + if (StringUtils.isNotBlank(cat)) { + params.add(new QueryParam("cat", cat)); + } + if (StringUtils.isNotBlank(source)) { + params.add(new QueryParam("source", Integer.valueOf(source))); + } + List sortParams = new ArrayList(2); + List allNearbys = statsIndexDao.findAllByParams(params, + sortParams); + return allNearbys; + } - - @Override - public List findAllStatsNocat(String yearmonth,String cat,String source) { - List params = new ArrayList(); - if (StringUtils.isNotBlank(yearmonth)) { - params.add(new QueryParam("yearmonth", yearmonth)); - } - if(StringUtils.isNotBlank(cat)){ - params.add(new QueryParam("cat", cat)); - } - if(StringUtils.isNotBlank(source)){ - params.add(new QueryParam("source", Integer.valueOf(source))); - } - List sortParams = new ArrayList(2); - List allNearbys = statsIndexDao.findAllByParams(params, - sortParams); - return allNearbys; - } - - @Override - public Integer findEarliestMonth(String city, String cat, String source) { - List params = new ArrayList(); - if(StringUtils.isNotBlank(cat)){ - params.add(new QueryParam("cat", cat)); - } - if(StringUtils.isNotBlank(source)){ - params.add(new QueryParam("source", Integer.valueOf(source))); - } - if(StringUtils.isNotBlank(city)){ - params.add(new QueryParam("city", city)); - } - List statsIndexList = statsIndexDao.findAllByParams(params, null, 0, Integer.MAX_VALUE, new String[]{"yearmonth"}); - Integer min = null; - for(StatsIndex statsIndex : statsIndexList){ - Integer yearMonth = Integer.valueOf(statsIndex.getYearmonth()); - if(min == null || yearMonth < min){ - min = yearMonth; - } - } - return min; - } + @Override + public Integer findEarliestMonth(String city, String cat, String source) { + List params = new ArrayList(); + if (StringUtils.isNotBlank(cat)) { + params.add(new QueryParam("cat", cat)); + } + if (StringUtils.isNotBlank(source)) { + params.add(new QueryParam("source", Integer.valueOf(source))); + } + if (StringUtils.isNotBlank(city)) { + params.add(new QueryParam("city", city)); + } + List statsIndexList = statsIndexDao.findAllByParams(params, null, 0, Integer.MAX_VALUE, new String[]{"yearmonth"}); + Integer min = null; + for (StatsIndex statsIndex : statsIndexList) { + Integer yearMonth = Integer.valueOf(statsIndex.getYearmonth()); + if (min == null || yearMonth < min) { + min = yearMonth; + } + } + return min; + } } diff --git a/projects/fangjia-service/src/main/java/com/fangjia/service/open/ApiUserBo.java b/projects/fangjia-service/src/main/java/com/fangjia/service/open/ApiUserBo.java index 8c09268bf..1f3da2050 100644 --- a/projects/fangjia-service/src/main/java/com/fangjia/service/open/ApiUserBo.java +++ b/projects/fangjia-service/src/main/java/com/fangjia/service/open/ApiUserBo.java @@ -28,6 +28,16 @@ public class ApiUserBo implements Serializable { private String priceType; private Integer isMonitor; + private String contact; //ÁªÏµÈË + + private String phone; //ÁªÏµÈËÊÖ»úºÅ + + private Integer isMonitorStatistic; + + private Integer isMonitorUsed; + + private Integer isWarnExpired; + public String getPriceType() { return priceType; } @@ -171,4 +181,44 @@ public class ApiUserBo implements Serializable { public void setIsMonitor(Integer isMonitor) { this.isMonitor = isMonitor; } + + public String getContact() { + return contact; + } + + public void setContact(String contact) { + this.contact = contact; + } + + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + + public Integer getIsMonitorStatistic() { + return isMonitorStatistic; + } + + public void setIsMonitorStatistic(Integer isMonitorStatistic) { + this.isMonitorStatistic = isMonitorStatistic; + } + + public Integer getIsMonitorUsed() { + return isMonitorUsed; + } + + public void setIsMonitorUsed(Integer isMonitorUsed) { + this.isMonitorUsed = isMonitorUsed; + } + + public Integer getIsWarnExpired() { + return isWarnExpired; + } + + public void setIsWarnExpired(Integer isWarnExpired) { + this.isWarnExpired = isWarnExpired; + } } diff --git a/projects/fangjia-service/src/main/java/com/fangjia/service/open/AuthorityBo.java b/projects/fangjia-service/src/main/java/com/fangjia/service/open/AuthorityBo.java index 7b29385d9..4b58254a6 100644 --- a/projects/fangjia-service/src/main/java/com/fangjia/service/open/AuthorityBo.java +++ b/projects/fangjia-service/src/main/java/com/fangjia/service/open/AuthorityBo.java @@ -32,6 +32,10 @@ public class AuthorityBo implements Serializable { private long curVisitedCount; private long totalVisitedCount; private Integer isCheckCount;//ÊÇ·ñ°´²éµÃ¼Æ·Ñ 1£ºÊÇ £¬0£º·ñ + + private int pubStatus; + + private int apiCode; public Map getResourceAuthorityMap() { return resourceAuthorityMap; @@ -158,7 +162,19 @@ public class AuthorityBo implements Serializable { this.totalVisitedCount = totalVisitedCount; } - - - + public int getPubStatus() { + return pubStatus; + } + + public void setPubStatus(int pubStatus) { + this.pubStatus = pubStatus; + } + + public int getApiCode() { + return apiCode; + } + + public void setApiCode(int apiCode) { + this.apiCode = apiCode; + } } diff --git a/projects/fangjia-service/src/main/java/com/fangjia/service/util/EvaluateParamMap.java b/projects/fangjia-service/src/main/java/com/fangjia/service/util/EvaluateParamMap.java index 0bc28d9f5..2bc49ea24 100644 --- a/projects/fangjia-service/src/main/java/com/fangjia/service/util/EvaluateParamMap.java +++ b/projects/fangjia-service/src/main/java/com/fangjia/service/util/EvaluateParamMap.java @@ -52,6 +52,9 @@ public class EvaluateParamMap { BUILD_TYPE_MAP.put("6", "ÁªÅűðÊû"); BUILD_TYPE_MAP.put("7", "µþ¼Ó±ðÊû"); BUILD_TYPE_MAP.put("8", "¹«Ô¢"); + BUILD_TYPE_MAP.put("9","ÁªÁÐסլ"); + BUILD_TYPE_MAP.put("10","»¨Ô°×¡Õ¬"); + BUILD_TYPE_MAP.put("11","¾ÉʽÀïŪ2"); HOUSE_PROPERTY_MAP.put("1","¸öÈ˲úȨ"); HOUSE_PROPERTY_MAP.put("2","¼¯Ìå²úȨ"); diff --git a/projects/fangjia-service/src/main/java/com/fangjia/service/util/kafka/KafkaProducerUtils.java b/projects/fangjia-service/src/main/java/com/fangjia/service/util/kafka/KafkaProducerUtils.java index 83439602a..b5a00d80f 100644 --- a/projects/fangjia-service/src/main/java/com/fangjia/service/util/kafka/KafkaProducerUtils.java +++ b/projects/fangjia-service/src/main/java/com/fangjia/service/util/kafka/KafkaProducerUtils.java @@ -2,6 +2,7 @@ package com.fangjia.service.util.kafka; import com.alibaba.fastjson.JSONObject; import com.fangjia.dal.mongo.tool.model.OpenUriLog; +import org.apache.commons.lang3.StringUtils; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.clients.producer.ProducerRecord; @@ -19,9 +20,13 @@ public class KafkaProducerUtils implements DisposableBean { public KafkaProducerUtils() { Properties properties = new Properties(); - properties.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.0.100:30092"); + properties.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.0.89:19092,192.168.0.90:19092,192.168.0.91:19092"); properties.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); properties.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); + properties.setProperty("session.timeout.ms", "15000"); + properties.setProperty("sasl.mechanism", "PLAIN"); + properties.setProperty("security.protocol", "SASL_PLAINTEXT"); + properties.setProperty("sasl.jaas.config", "org.apache.kafka.common.security.plain.PlainLoginModule required username=\"admin\" password=\"Goojia123456\";"); this.producer = new KafkaProducer(properties); } @@ -35,6 +40,12 @@ public class KafkaProducerUtils implements DisposableBean { ex.printStackTrace(); } } + public void send(String topic,String msg){ + if (StringUtils.isNotBlank(topic) && StringUtils.isNotBlank(msg)){ + ProducerRecord record = new ProducerRecord(topic, msg); + this.producer.send(record); + } + } @Override public void destroy() throws Exception { diff --git a/projects/fangjia-static/src/main/java/com/fangjia/stc2/FileDao.java b/projects/fangjia-static/src/main/java/com/fangjia/stc2/FileDao.java index fcda0b3e4..9b22b5672 100644 --- a/projects/fangjia-static/src/main/java/com/fangjia/stc2/FileDao.java +++ b/projects/fangjia-static/src/main/java/com/fangjia/stc2/FileDao.java @@ -37,8 +37,8 @@ public class FileDao { IMPORTANT_CATEGORY = Arrays.asList(System.getProperty("fangjia.important.category", "district,shop,office,avatar,flash,user_house,upload,news,attachment").split(",")); try { - filesCollection = new Mongo("fs.mongo.db.fangjia.com", Integer.getInteger("fs.mongo.port", 27017)).getDB("fangjia_fs").getCollection("files"); - gridFs = new GridFS(filesCollection.getDB(), "fangjia_fs"); + filesCollection = new Mongo("fs.mongo.db.fangjia.com", Integer.getInteger("fs.mongo.port", 27017)).getDB("fangjia").getCollection("files"); + gridFs = new GridFS(filesCollection.getDB(), "fangjia"); cappedCollection = new Mongo("capped.mongo.db.fangjia.com", Integer.getInteger("capped.mongo.port", 27017)).getDB("fangjia_fs").getCollection("files_capped"); } catch (Exception e) { e.printStackTrace(); diff --git a/projects/fangjia-static/src/main/webapp/js/fangjia/v5/register.js b/projects/fangjia-static/src/main/webapp/js/fangjia/v5/register.js index 42db3b6a2..3457900c1 100644 --- a/projects/fangjia-static/src/main/webapp/js/fangjia/v5/register.js +++ b/projects/fangjia-static/src/main/webapp/js/fangjia/v5/register.js @@ -239,7 +239,9 @@ $(function() { if(refererUrl.endWith("gujia/report")){ refererUrl = refererUrl+"?fangjia=true"; } - window.location.href = wwwUrl + "/user/register/success?backUrl="+refererUrl; + //æˆ�功页é�¢ + // window.location.href = wwwUrl + "/user/register/success?backUrl="+refererUrl; + window.location.href = refererUrl } else { if (re.msg == "输入的验è¯�ç �ä¸�正确,请é‡�新输入") { $(".smscode_err").html("短信验è¯�ç �错误"); diff --git a/projects/fangjia-static/src/main/webapp/style/fangjia/v6/reportNew.css b/projects/fangjia-static/src/main/webapp/style/fangjia/v6/reportNew.css index 780bb48dc..e7ecf7fb2 100644 --- a/projects/fangjia-static/src/main/webapp/style/fangjia/v6/reportNew.css +++ b/projects/fangjia-static/src/main/webapp/style/fangjia/v6/reportNew.css @@ -6,10 +6,10 @@ .main_reportNew{width: 1200px;margin: auto;margin-top: 100px;overflow: hidden;position: relative;} /*.main_left_reportNew{width: 1200px;}*/ -.evaluationBox{height: 550px;} +.evaluationBox{height: auto;} .evaluation_title {height: 50px;font-size: 25px;font-weight: 400;display: inline-flex;line-height: 50px;} .evaluation_title i { width: 43px;height: 50px;background: url(../../../images/fangjia/v6/4-2-3.png);background-size: 33px 33px;background-repeat: no-repeat;background-position: left;} -.evaluation_content {height: 500px;background: url(../../../images/fangjia/v6/4-2-12.png);background-size:100% 100%;position: relative;margin-top: 30px;display: block;} +.evaluation_content {height: 600px;background: url(../../../images/fangjia/v6/4-2-12.png);background-size:100% 100%;position: relative;margin-top: 30px;display: block;} .evaluation_inputInfo {overflow: hidden;} .evaluation_inputInfo_table{height: 520px;margin-top: 80px;} .evaluation_inputInfo_flex{display: flex;height: 40px;margin-top: 50px;} diff --git a/projects/fangjia-static/src/main/webapp/style/fangjia/v6/seoInfo.css b/projects/fangjia-static/src/main/webapp/style/fangjia/v6/seoInfo.css new file mode 100644 index 000000000..83c2d72fe --- /dev/null +++ b/projects/fangjia-static/src/main/webapp/style/fangjia/v6/seoInfo.css @@ -0,0 +1,37 @@ +@charset "utf-8"; +/* CSS Document */ +.main { width: 1200px;margin: auto; margin-top: 100px;overflow: hidden;position: relative;} +.main_left {margin: auto;} +.topic {padding: 40px 0;border-bottom: solid 1px #e5e5e5;} +.topic_top {font-size: 18px;margin-bottom: 20px;align-items: center;display: flex;float: left;} +.topic_top i {width: 30px;height: 36px;display: inline-flex;background: url(../../../images/fangjia/v6/4-2-13.png) no-repeat left bottom;margin-left: -10px;} +.overview01 .overview_left{margin-bottom: 80px;} +.overview01 .overview_left p { margin-bottom: 10px;width: 100%; text-align: justify;font-size: 20px;line-height: 30px;} +.overview01 .overview_left p label {color: #3c3f46;font-size: 24px;font-weight: 500;} +.overview01 .overview_left p i {width: 11px;height: 30px;background: url(../../../images/fangjia/v6/address.png) no-repeat center center;float: left;margin-right: 5px;} +.overview01 .overview_left p{font-size: 16px;} + +.price_div{display: flex;float: left;flex-direction: row;justify-content: flex-start;width: 1200px; margin: auto auto; padding-bottom: 10px;} +.price_div ul{width:25%;} +.price_div ul li{color: #878682;} +.price_div ul li .unit_price{color: #db4c3f;font-size: 32px;font-weight: bold;line-height: 50px;} +.price_div ul li .dw{color: #db4c3f;font-size: 16px;} +.price_div ul li .up{ color: #db4c3f;} +.price_div ul li .down{color:#00ae66;} +.price_div ul li .hb_tb{font-size: 22px;line-height: 50px;} +.price_div ul li .down i {background: url(../../../images/fangjia/v6/down.png) no-repeat left center;} +.price_div ul li .up i {background: url(../../../images/fangjia/v6/up.png) no-repeat left center;} + + +.districtMap{width:100%;height:400px;} +/* 地图样å¼� */ +.mark-icon-box .mark-icon {width: 20px;height: 30px;display: block;cursor: pointer;font-size: 14px;color: #fff;font-weight: bold;text-align: center;line-height: 24px;background: url(../../../images/fangjia/v5/dw.png) no-repeat;} +.mark-icon-box { width: 24px; height: 30px; position: absolute; z-index: 98; } +.mark-icon-box .mark-icon:hover, .mark-icon-box .mark-icon-h { background: url(../../../images/fangjia/v5/dw_h.png) no-repeat ; } + +.mark-tip {font-size: 14px;position: absolute;z-index: 99;margin-top: -74px;margin-left: -20px;} +.mark-tip .title1 {line-height: 20px;color: #000;background: #fff;padding: 5px 40px 5px 15px;border-radius: 5px;box-shadow: 3px 3px 8px #888;height: 20px;} +.mark-tip .title1 span {display: inline-block;max-width: 170px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;margin-right: 25px;} +.mark-tip .title1 b { font-weight: normal; display: block; position: absolute; top: 5px; right: 10px; } +.mark-tip .icon { width: 21px; height:14px; background: url(../../../images/fangjia/v5/sj.png) no-repeat ; position: absolute; bottom: -14px; left: 20px; } +