宏信相关

This commit is contained in:
2025-12-25 08:53:00 +08:00
parent 469ee5f2ed
commit 5abf2ddaaa
7 changed files with 712 additions and 4 deletions
@@ -0,0 +1,82 @@
package com.fangjia.core.util;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
@Data
public class PriceData {
private String yearmonth;
private Double price;
private Double volume; // 新增成交量字段
public PriceData() {}
public PriceData(String yearmonth, Double price) {
this.yearmonth = yearmonth;
this.price = price;
}
public PriceData(String yearmonth, Double price, Double volume) {
this.yearmonth = yearmonth;
this.price = price;
this.volume = volume;
}
public static List<PriceData> getSampleData() {
List<PriceData> data = new ArrayList<>();
double basePrice = 22000;
double minPrice = basePrice * (1 - 0.04);
double maxPrice = basePrice * (1 + 0.04);
Random random = new Random();
for (int i = 0; i < 2; i++) {
int year = 2024;
int month = i + 4;
if (month > 12) {
year++;
month -= 12;
}
String date = String.format("%d-%02d", year, month);
double price = minPrice + random.nextDouble() * (maxPrice - minPrice);
double volume = 100 + random.nextInt(100);
data.add(new PriceData(date, price, volume));
System.out.println(data.get(i));
}
return data;
}
public static List<PriceData> getSampleData(double basePrice) {
List<PriceData> data = new ArrayList<>();
double minPrice = basePrice * (1 - 0.02);
double maxPrice = basePrice * (1 + 0.02);
Random random = new Random();
for (int i = 0; i < 12; i++) {
int year = 2025;
int month = i + 1;
if (month > 12) {
year++;
month -= 12;
}
String date = String.format("%d-%02d", year, month);
double price = minPrice + random.nextDouble() * (maxPrice - minPrice);
double volume = 100 + random.nextInt(200);
data.add(new PriceData(date, price, volume));
System.out.println(data.get(i));
}
return data;
}
public static List<PriceData> getSampleData2() {
List<PriceData> data = new ArrayList<>();
data.add(new PriceData("2025-01", 11110.0, 90.0));
data.add(new PriceData("2025-02", 11115.0, 110.0));
data.add(new PriceData("2025-03", 11112.0, 95.0));
data.add(new PriceData("2025-04", 11120.0, 150.0));
data.add(new PriceData("2025-05", 11118.0, 140.0));
return data;
}
}
@@ -0,0 +1,49 @@
package com.fangjia.core.util;
import lombok.Builder;
import lombok.Data;
import java.util.List;
/**
* @author shenjian
* @since 2024/12/17
*/
@Data
public class PriceDto {
private Integer id;
private Integer avgPrice;//本周均价
private PriceTrend priceTrend; //均价走势
private List<RentPrice> rentPrices;//本月租金
private PriceTrend rentTrend;//租金走势
@Data
@Builder
public static class RentPrice {
private String name;
private Integer price;
}
@Data
public static class PriceTrend {
private List<String> categories;
private List<Series> series;
private List<DoubleSeries> doubleSeries;
}
@Data
public static class Series {
private String name;
private List<Integer> data;
}
@Data
public static class DoubleSeries {
private String name;
private List<Double> data;
}
}
@@ -0,0 +1,316 @@
package com.fangjia.core.util;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
* SVG工具类,用于生成价格趋势的SVG图表
*/
public class SvgUtils {
// SVG画布尺寸
private static final int WIDTH = 800;
private static final int HEIGHT = 500;
private static final int PADDING = 60;
// 生成SVG折线图(支持多条线),新增decimalPlaces参数控制Y轴小数位
public static String generatePriceTrendSvg(List<List<PriceData>> dataSets, List<String> labels, String title, String subtitle, int decimalPlaces) {
if (dataSets.isEmpty() || dataSets.get(0).isEmpty()) {
return "<svg xmlns='http://www.w3.org/2000/svg' width='" + WIDTH + "' height='" + HEIGHT + "'></svg>";
}
// 过滤为空的数据
dataSets = dataSets.stream()
.map(innerList -> innerList.stream()
.filter(priceData -> priceData != null && priceData.getPrice() != null)
.collect(Collectors.toList()))
.collect(Collectors.toList());
// 计算价格和时间的范围
double minPrice = dataSets.stream()
.flatMap(List::stream)
.filter((p) -> p != null && p.getPrice() != null)
.mapToDouble(PriceData::getPrice)
.min()
.orElse(0) * 0.8;
double maxPrice = dataSets.stream()
.flatMap(List::stream)
.filter((p) -> p != null && p.getPrice() != null)
.mapToDouble(PriceData::getPrice)
.max()
.orElse(1) * 1.2;
double buffer = 0.1;
minPrice = minPrice * (1 - buffer);
maxPrice = maxPrice * (1 + buffer);
// 如果decimalPlaces为0,调整minPrice和maxPrice为整数等差
// if (decimalPlaces == 0) {
// long step = calculateStep((long) Math.ceil(maxPrice) - (long) Math.floor(minPrice));
// minPrice = Math.floor(minPrice / step) * step;
// maxPrice = Math.ceil(maxPrice / step) * step;
// }
// 解析最小和最大日期
String minYearMonth = dataSets.stream()
.flatMap(List::stream)
.map(PriceData::getYearmonth)
.min(String::compareTo)
.orElse("2024-08");
String maxYearMonth = dataSets.stream()
.flatMap(List::stream)
.map(PriceData::getYearmonth)
.max(String::compareTo)
.orElse("2025-01");
// 构建SVG内容
StringBuilder svg = new StringBuilder();
svg.append(String.format("<svg xmlns='http://www.w3.org/2000/svg' width='%d' height='%d'>", WIDTH, HEIGHT));
svg.append(String.format("<rect width='%d' height='%d' fill='#ffffff'/>", WIDTH, HEIGHT));
// 添加标题和副标题
svg.append(String.format("<text x='%d' y='%d' font-size='20' font-family='Arial' fill='#333333' font-weight='bold' text-anchor='middle'>%s</text>",
WIDTH / 2, 30, title));
svg.append(String.format("<text x='%d' y='%d' font-size='14' font-family='Arial' fill='#666666' text-anchor='middle'>%s</text>",
WIDTH / 2, 50, subtitle));
// 画虚线网格线和坐标轴
svg.append(drawGrid(minYearMonth, maxYearMonth, minPrice, maxPrice, decimalPlaces));
svg.append(drawAxis(minYearMonth, maxYearMonth, minPrice, maxPrice, decimalPlaces));
// 画多条折线和图例
String[] colors = {"#66B3FF", "#FF6666", "#FFA500", "#8A2BE2"};
for (int i = 0; i < dataSets.size(); i++) {
svg.append(drawSmoothLine(dataSets.get(i), minYearMonth, maxYearMonth, minPrice, maxPrice, colors[i % colors.length], decimalPlaces));
svg.append(String.format("<rect x='%d' y='%d' width='10' height='10' fill='%s'/>", 650, 60 + i * 20, colors[i % colors.length]));
svg.append(String.format("<text x='%d' y='%d' font-size='12' fill='#333333'>%s</text>", 670, 70 + i * 20, labels.get(i)));
}
svg.append("</svg>");
return svg.toString();
}
// 绘制平滑折线
private static String drawSmoothLine(List<PriceData> data, String minYearMonth, String maxYearMonth, double minPrice, double maxPrice, String color, int decimalPlaces) {
// if (data.size() < 2) return "";
StringBuilder path = new StringBuilder("<path d='M");
StringBuilder pointsAndLabels = new StringBuilder();
int totalMonths = getMonthIndex(maxYearMonth) - getMonthIndex(minYearMonth) + 1;
if (data.size() == 1) {
// 处理只有一个数据点的情况
PriceData point = data.get(0);
int monthIndex = Math.max(0, Math.min(totalMonths - 1, getMonthIndex(point.getYearmonth()) - getMonthIndex(minYearMonth)));
int x = WIDTH / 2;
int y = HEIGHT - PADDING - (HEIGHT - 2 * PADDING) / 2;
// int y = HEIGHT - PADDING - (int) ((point.getPrice() - minPrice) * (HEIGHT - 2 * PADDING) / (maxPrice - minPrice));
pointsAndLabels.append(String.format("<circle cx='%d' cy='%d' r='3' fill='%s'/>", x, y, color));
pointsAndLabels.append(String.format("<text x='%d' y='%d' font-size='10' fill='%s'>%." + decimalPlaces + "f</text>",
x + 5, y - 5, color, point.getPrice()));
path.append("M").append(x).append(",").append(y);
} else if (data.size() > 1) {
for (int i = 0; i < data.size() - 1; i++) {
PriceData point1 = data.get(i);
PriceData point2 = data.get(i + 1);
int monthIndex1 = Math.max(0, Math.min(totalMonths - 1, getMonthIndex(point1.getYearmonth()) - getMonthIndex(minYearMonth)));
int monthIndex2 = Math.max(0, Math.min(totalMonths - 1, getMonthIndex(point2.getYearmonth()) - getMonthIndex(minYearMonth)));
int x1 = PADDING + (monthIndex1 * (WIDTH - 2 * PADDING) / (totalMonths - 1));
int y1 = HEIGHT - PADDING - (int) ((point1.getPrice() - minPrice) * (HEIGHT - 2 * PADDING) / (maxPrice - minPrice));
int x2 = PADDING + (monthIndex2 * (WIDTH - 2 * PADDING) / (totalMonths - 1));
int y2 = HEIGHT - PADDING - (int) ((point2.getPrice() - minPrice) * (HEIGHT - 2 * PADDING) / (maxPrice - minPrice));
int controlX1 = x1 + (x2 - x1) / 3;
int controlY1 = y1;
int controlX2 = x2 - (x2 - x1) / 3;
int controlY2 = y2;
if (i == 0) path.append(x1).append(",").append(y1);
path.append(" C").append(controlX1).append(",").append(controlY1).append(" ").append(controlX2).append(",").append(controlY2).append(" ").append(x2).append(",").append(y2);
pointsAndLabels.append(String.format("<circle cx='%d' cy='%d' r='3' fill='%s'/>", x1, y1, color));
pointsAndLabels.append(String.format("<text x='%d' y='%d' font-size='10' fill='%s'>%." + decimalPlaces + "f</text>",
x1 + 5, y1 - 5, color, point1.getPrice()));
}
PriceData lastPoint = data.get(data.size() - 1);
int lastMonthIndex = Math.max(0, Math.min(totalMonths - 1, getMonthIndex(lastPoint.getYearmonth()) - getMonthIndex(minYearMonth)));
int lastX = PADDING + (lastMonthIndex * (WIDTH - 2 * PADDING) / (totalMonths - 1));
int lastY = HEIGHT - PADDING - (int) ((lastPoint.getPrice() - minPrice) * (HEIGHT - 2 * PADDING) / (maxPrice - minPrice));
pointsAndLabels.append(String.format("<circle cx='%d' cy='%d' r='3' fill='%s'/>", lastX, lastY, color));
pointsAndLabels.append(String.format("<text x='%d' y='%d' font-size='10' fill='%s'>%." + decimalPlaces + "f</text>",
lastX + 5, lastY - 5, color, lastPoint.getPrice()));
}
path.append("' fill='none' stroke='").append(color).append("' stroke-width='2'/>");
path.append(pointsAndLabels);
return path.toString();
}
// 绘制网格线
private static String drawGrid(String minYearMonth, String maxYearMonth, double minPrice, double maxPrice, int decimalPlaces) {
StringBuilder grid = new StringBuilder();
double step = calculateYStep(minPrice, maxPrice, decimalPlaces);
int numSteps = (int) ((maxPrice - minPrice) / step) + 1;
for (int i = 0; i < numSteps; i++) {
double price = minPrice + i * step;
if (price > maxPrice) break;
int y = HEIGHT - PADDING - (int) ((price - minPrice) * (HEIGHT - 2 * PADDING) / (maxPrice - minPrice));
grid.append(String.format("<line x1='%d' y1='%d' x2='%d' y2='%d' stroke='#e0e0e0' stroke-dasharray='5,5'/>",
PADDING, y, WIDTH - PADDING, y));
}
return grid.toString();
}
// 绘制坐标轴
private static String drawAxis(String minYearMonth, String maxYearMonth, double minPrice, double maxPrice, int decimalPlaces) {
StringBuilder axis = new StringBuilder();
// X轴
axis.append(String.format("<line x1='%d' y1='%d' x2='%d' y2='%d' stroke='#333333' stroke-width='2'/>",
PADDING, HEIGHT - PADDING, WIDTH - PADDING, HEIGHT - PADDING));
axis.append(String.format("<line x1='%d' y1='%d' x2='%d' y2='%d' stroke='#333333' stroke-width='2'/>",
PADDING, PADDING, PADDING, HEIGHT - PADDING));
// X轴刻度
int totalMonths = getMonthIndex(maxYearMonth) - getMonthIndex(minYearMonth) + 1;
for (int i = 0; i < totalMonths; i++) {
int x;
if (totalMonths == 1) {
// 当只有一个月时,将刻度放在中间位置
x = PADDING + (WIDTH - 2 * PADDING) / 2;
} else {
x = PADDING + i * (WIDTH - 2 * PADDING) / (totalMonths - 1);
}
String monthLabel = getMonthLabel(minYearMonth, i);
axis.append(String.format("<line x1='%d' y1='%d' x2='%d' y2='%d' stroke='#333333' stroke-width='1'/>",
x, HEIGHT - PADDING + 5, x, HEIGHT - PADDING));
axis.append(String.format("<text x='%d' y='%d' font-size='12' fill='#333333' text-anchor='middle'>%s</text>",
x, HEIGHT - PADDING + 20, monthLabel));
}
// Y轴刻度
double step = calculateYStep(minPrice, maxPrice, decimalPlaces);
int numSteps = (int) ((maxPrice - minPrice) / step) + 1;
for (int i = 0; i < numSteps; i++) {
double price = minPrice + i * step;
int y = HEIGHT - PADDING - (int) ((price - minPrice) * (HEIGHT - 2 * PADDING) / (maxPrice - minPrice));
axis.append(String.format("<line x1='%d' y1='%d' x2='%d' y2='%d' stroke='#333333' stroke-width='1'/>",
PADDING - 5, y, PADDING, y));
axis.append(String.format("<text x='%d' y='%d' font-size='12' fill='#333333' text-anchor='end'>%." + decimalPlaces + "f</text>",
PADDING - 10, y + 5, price));
}
return axis.toString();
}
// 计算Y轴步长
private static double calculateYStep(double minPrice, double maxPrice, int decimalPlaces) {
double range = maxPrice - minPrice;
if (decimalPlaces == 0) {
return calculateStep((long) range);
}
double step = range / 10.0; // 默认10个间隔
double scale = Math.pow(10, decimalPlaces);
return Math.round(step * scale) / scale;
}
// 计算整数步长
private static long calculateStep(long range) {
long step = (long) Math.pow(10, Math.floor(Math.log10(range)));
if (range / step < 4) step /= 2;
else if (range / step > 8) step *= 2;
return step;
}
// 获取月份标签和索引(保持不变)
private static String getMonthLabel(String minYearMonth, int offset) {
int totalMonths = getMonthIndex(minYearMonth);
int targetMonthIndex = totalMonths + offset;
int year = 2024 + targetMonthIndex / 12;
int month = targetMonthIndex % 12 + 1;
return String.format("%d-%02d", year, month);
}
private static int getMonthIndex(String yearMonth) {
int year = Integer.parseInt(yearMonth.substring(0, 4));
int month = Integer.parseInt(yearMonth.substring(5));
return (year - 2024) * 12 + (month - 1);
}
public static void generateSvg(String svgContent, String outputPath) {
try (FileWriter writer = new FileWriter(outputPath)) {
writer.write(svgContent);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 对齐已有系列数据与新的时间轴
*/
public static void alignSeriesData(List<String> newCategories, List<PriceDto.DoubleSeries> series, PriceDto.PriceTrend rentTrend) {
for (PriceDto.DoubleSeries s : series) {
List<Double> originalData = s.getData();
List<String> originalCategories = new ArrayList<>(rentTrend.getCategories()); // 假设原始时间轴可从别处获取
List<Double> alignedData = new ArrayList<>();
// 根据新的时间轴对齐数据
for (String date : newCategories) {
int index = originalCategories.indexOf(date);
if (index >= 0 && index < originalData.size()) {
alignedData.add(originalData.get(index));
} else {
alignedData.add(null); // 日期不存在时补 null
}
}
s.setData(alignedData);
}
}
// 测试方法
public static void main(String[] args) {
List<PriceData> data1 = PriceData.getSampleData(5200);
List<List<PriceData>> dataSets = new ArrayList<>();
dataSets.add(data1);
String name = "新世纪大厦";
List<String> labels = Arrays.asList(name);
String title = "价格走势图";
String subtitle = "2024-12 至 2025-11";
// // 测试小数位为2
// String svgWithoutDecimals = generatePriceTrendSvg(dataSets, labels, title, subtitle, 2);
// System.out.println("With 2 decimal places:");
// System.out.println(svgWithoutDecimals);
// 测试小数位为0(整数等差)
String svgWithoutDecimals = generatePriceTrendSvg(dataSets, labels, title, subtitle, 0);
System.out.println("With 0 decimal places (integer steps):");
System.out.println(svgWithoutDecimals);
try {
generateSvg(svgWithoutDecimals, name + ".svg");
System.out.println("PNG image generated successfully at: price_trend.png");
} catch (Exception e) {
e.printStackTrace();
}
// String locationStr = "114.407048,30.481859";
// String[] location = locationStr.split(",");
// Double lng = Double.parseDouble(location[0]);
// Double lat = Double.parseDouble(location[1]);
// String mapUrl = "https://restapi.amap.com/v3/staticmap?location=" + lng + "," + lat
// + "&zoom=14&size=780*300&markers=mid,,A:" + lng + "," + lat
// + "&key=ee95e52bf08006f63fd29bcfbcf21df0";
// System.out.println(mapUrl);
}
}
+6
View File
@@ -602,5 +602,11 @@
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>com.fasterxml.jackson.core</groupId>-->
<!-- <artifactId>jackson-core</artifactId>-->
<!-- <version>2.9.9</version>-->
<!-- <scope>compile</scope>-->
<!-- </dependency>-->
</dependencies>
</project>
@@ -0,0 +1,62 @@
package com.fangjia.script.gj.test
import com.fangjia.script.commData.CommonDatautils
import com.fangjia.script.util.DateUtils
import com.fangjia.script.util.ExcelUtils
import com.fangjia.script.util.GeoHelper
class JingDongTest {
static main(args) {
// def task = new JingDongTest()
// def path = "D:\\数据\\京东\\京东测试数据.xlsx"
// task.run(path)
// task.addPrice(path)
// 120.12063,30.281452
// 120.120419,30.2767
// 120.116349,30.29144
// 120.137169,30.272963
// 120.108109,30.265553
ExcelUtils.modify("C:\\Users\\gaojuan\\Downloads\\商铺出租信息 (3).xlsx",{d->
if(d['J']){
def arrs = d['J'].split(",")
def distance = GeoHelper.GetDistance(arrs[1].toString().toDouble(), arrs[0].toString().toDouble(), 22.554693, 113.869516)
d['F'] = distance
}
})
}
def run(path){
def cityMap = ["北京":"大兴","厦门":"思明","泉州":"丰泽","安顺":"西秀"]
def rets = []
rets << ["城市","区域","名称","地址","高德经度","高德纬度","均价"]
for(def m : cityMap) {
println m.key +" "+m.value
def districts = CommonDatautils.findAllRegionDistricts(m.key, m.value, "district", ["city", "region", "name", "address", "lng", "lat"]);
for(def d : districts){
if(d.lng){
println d
rets << [d.city, d.region, d.name, d.address, d.lng/10000000000.0, d.lat/10000000000.0]
}
}
}
ExcelUtils.write(path, rets, "数据")
}
def addPrice(path){
ExcelUtils.multiThreadingModify(path,{d->
if(!d['G']){
def dbo = CommonDatautils.findDistrictPrice(d['A'], d['B'], d['C'])
if(dbo){
d['G'] = dbo.avg_price_2b
d['H'] = DateUtils.formatDateByPattern(dbo.weekend,"yyyy-MM-dd")
}
}
})
}
}
@@ -1,22 +1,27 @@
package com.fangjia.script.jiangnanblank
import com.fangjia.core.util.HttpRequest
import com.fangjia.core.util.PriceData
import com.fangjia.core.util.SvgUtils
import com.fangjia.script.ccbevaluation.CcbCommonUtils
import com.fangjia.script.commData.CommonDatautils
import com.fangjia.script.gj.OpenApiUtils
import com.fangjia.script.gj.district.FangjiaClientUtils
import com.fangjia.script.util.ExcelUtils
import com.fangjia.script.util.OpenApiClient
import groovy.json.JsonBuilder
import groovy.sql.Sql
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import groovy.json.JsonOutput
/**
* Created by gaojuan on 2017/12/7.
*/
class TestEvaluation {
def sql = Sql.newInstance(
"jdbc:mysql://192.168.0.92:3306/fangjiatong?useSSL=false&serverTimezone=Asia/Shanghai",
"jdbc:mysql://192.168.0.92:3306/fangjiatong?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai",
"goojia",
"G0ojia123456!@#",
"com.mysql.cj.jdbc.Driver"
@@ -357,7 +362,7 @@ class TestEvaluation {
if(d['B'] == "公寓"){
buildType = 8
}else if(d['B'] == "别墅"){
buildType = 4
buildType = 11
}else if(d['B'] == "商铺"){
buildType = 1
}else if(d['B'] == "办公楼"){
@@ -365,11 +370,13 @@ class TestEvaluation {
}
def lat = dist.lat/10000000000.0
def lng = dist.lng/10000000000.0
def cat = 5
if(buildType==3 || buildType==8 || buildType ==4){
def cat = 6
if(buildType==3 || buildType==8 || buildType ==11){
cat = 1
}else if(buildType == 1){
cat = 4
}else if(buildType == 2){
cat = 6
}
def date = new Date()
rets << [d['E'], dist.city, dist.region, dist.name, dist.address,buildType,d['I'], d['J'].toString().toDouble().toInteger(), lng, lat, d['F'], date, date, cat, d['K'].toString().toDouble().toInteger()]
@@ -394,14 +401,159 @@ class TestEvaluation {
def addEvaluationDetail(){
def rets = []
def detailList = ExcelUtils.read("D:\\数据\\宏信息\\宏信房源台账-基准价-详情.xlsx", 0 , 1)
ExcelUtils.modify("D:\\数据\\宏信息\\宏信项目-最终.xlsx", { d ->
if (d['G']) {
def dist = CommonDatautils.findDistrictById(d['G'])
if (dist) {
def ret = []
ret << d['L'].toString().toDouble().toInteger()
def houses = []
if(["住宅","别墅","公寓"].contains(d["B"])){
def propertyType = 0
if(d["B"] == "别墅"){
propertyType = 1
}
def avgPrice = d['K']
def minPrice = null
def maxPrice = null
if(avgPrice){
minPrice = (int)(avgPrice - avgPrice * 0.1)
maxPrice = (int)(avgPrice + avgPrice * 0.1)
}
houses = OpenApiClient.newHouseAction(dist.city, dist.region, dist.name, propertyType.toString(), minPrice, maxPrice, 5)
}
if(houses){
ret << houses
}else{
ret << []
}
if(d['K']){
ret << createTrend(d['K'].toString().toDouble().toInteger(), d['A'])
}else{
ret << '{"trendSvg":""}'
}
ret << []
ret << "上海宏信建设发展有限公司"
ret << new Date()
ret << new Date()
ret << 1
ret << d['A']
ret << [createAttachment(detailList, d['G'], d['B'], dist)]
rets.add(ret)
def sqlstring = "insert into evaluation_edit_data(evaluation_id, house_samples, market_analysis, custom_properties, company, create_time, update_time, validity_period, subject_name, attachments) values (?,?,?,?,?,?,?,?,?,?)"
sql.withBatch(1, sqlstring){ ps->
for(def r : rets) {
def houseSamplesJson = null
if (r[1]) {
// 修复中文转义
houseSamplesJson = fixUnicodeEscapes(JsonOutput.toJson(r[1]))
}
def marketAnalysisJson = null
if (r[2]) {
// 修复中文转义
marketAnalysisJson = fixUnicodeEscapes(JsonOutput.toJson(r[2]))
}
def customPropertiesJson = r[1] ? JsonOutput.toJson(r[3]) : null
def attachmentsJson = null
if(r[9]){
// 修复中文转义
attachmentsJson = fixUnicodeEscapes(JsonOutput.toJson(r[9]))
}
ps.addBatch(r[0], houseSamplesJson, marketAnalysisJson, customPropertiesJson, r[4], r[5], r[6], r[7], r[8], attachmentsJson)
ps.toString()
}
}
}
}
});
}
def createTrend(price, name){
List<PriceData> data1 = PriceData.getSampleData(price);
List<List<PriceData>> dataSets = new ArrayList<>();
dataSets.add(data1);
List<String> labels = Arrays.asList(name);
def priceTrendMap = [:]
def categories = []
def priceData = []
for(PriceData pd : data1){
categories << pd.yearmonth
priceData << (int)pd.price
}
priceTrendMap.put("categories", categories)
priceTrendMap.put("series", [["name":name,"data":priceData]])
String title = "价格走势图";
String subtitle = categories[0] + " 至 "+categories[categories.size()-1];
// 测试小数位为0(整数等差)
String svgWithoutDecimals = SvgUtils.generatePriceTrendSvg(dataSets, labels, title, subtitle, 0);
return ["avgPrice":price, "priceTrend":priceTrendMap,"trendSvg":svgWithoutDecimals]
}
def createAttachment(detailList, id, type, dist){
def items = []
for(def data : detailList){
if(data["I"]==id && type==data['D']){
def totalPrice = (int)(data['H'] * data['N'])
items << ["city":dist.city, "district":dist.region, "address":data['B'], "area":data['H'], "unitPrice":data['N'].toString().toDouble().toInteger(), "totalPrice":totalPrice]
}
}
def time = new Date().getTime()
def resMap = ["id":"attachment_"+time, "title": "出售资产价格清单","type": 1,"editing": false,"items":items]
return resMap
}
def fixUnicodeEscapes(jsonString){
if (!jsonString){
return jsonString
}
def result = new StringBuilder()
def matcher = jsonString =~ /\\u([0-9a-fA-F]{4})/
def lastIndex = 0
while (matcher.find()) {
// 添加前面的部分
result.append(jsonString.substring(lastIndex, matcher.start()))
// 转换Unicode转义字符
String hex = matcher.group(1)
int codePoint = Integer.parseInt(hex, 16)
// 检查是否是中文字符(常用中文字符范围)
// 中文Unicode范围:0x4E00-0x9FFF,0x3400-0x4DBF,0x20000-0x2A6DF等
if ((codePoint >= 0x4E00 && codePoint <= 0x9FFF) ||
(codePoint >= 0x3400 && codePoint <= 0x4DBF)) {
// 是中文,转换为实际字符
result.append(new String(Character.toChars(codePoint)))
} else {
// 不是中文,保留转义格式
result.append("\\u").append(hex)
}
lastIndex = matcher.end()
}
// 添加剩余部分
result.append(jsonString.substring(lastIndex))
return result.toString()
}
@@ -1607,6 +1607,47 @@ public class OpenApiClient {
public static def newHouseAction(String city, String district, String name, String propertyType, Integer minPrice, Integer maxPrice, Integer pageSize) {
try {
Map<String, Object> params = new HashMap<String, Object>();
params.put("city", city);
params.put("district", district);
params.put("name", name)
params.put("token", TOKEN);
params.put("propertyType", propertyType)
params.put("showSource", "1")
// if(minPrice){
// params.put("minPrice", minPrice)
// }
// if(maxPrice){
// params.put("maxPrice", maxPrice)
// }
// if(pageSize){
// params.put("maxPrice", pageSize)
// }
String content = new HttpRequest().get("http://open.fangjia.com/property/sellCase", params, "utf-8")
JSONObject result = JSONObject.fromObject(content);
while (result == null) {
result = HttpRequestUtil.getJsonContent("http://open.fangjia.com/property/sellCase", params, "utf-8")
println("${city} ${name} 程序调用异常")
Thread.sleep(6000)
}
if (result.getInt("code") == 200) {
return result.get("result");
} else if (result.getInt("code") !=0) {
println("${city} ${name}")
}
} catch (Exception e) {
println("${city} ${name} ${e.getMessage()}")
e.printStackTrace();
}
return null
}
public static def houseAroundBylocationAction(location, size, propertyType, houseType, pageSize) {
def url ="https://open.fangjia.com/house/around?location="+location+"&size="+size+"&pageSize="+pageSize+"&propertyType="+propertyType+"&houseType="+houseType