luo
2023-12-25 23c4967b4cb8dbce8277f830f7152d315c5a4a57
guns-admin/src/main/java/com/stylefeng/guns/modular/system/service/impl/HouseResourceService.java
@@ -3,16 +3,27 @@
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.internal.util.codec.Base64;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stylefeng.guns.core.util.ToolUtil;
import com.stylefeng.guns.modular.file.OSSService;
import com.stylefeng.guns.modular.system.dao.HouseResourceMapper;
import com.stylefeng.guns.modular.system.model.*;
import com.stylefeng.guns.modular.system.service.*;
import com.stylefeng.guns.modular.system.util.ResultUtil;
import com.stylefeng.guns.modular.system.util.WxAppletTools;
import com.stylefeng.guns.modular.system.warpper.PointLocation;
import com.stylefeng.guns.modular.system.warpper.req.AddHouseReq;
import com.stylefeng.guns.modular.system.warpper.req.HouseQuery;
import com.stylefeng.guns.modular.system.warpper.req.SearchHouseResourceReq;
import com.stylefeng.guns.modular.system.warpper.req.UserInfoQuery;
import com.stylefeng.guns.modular.system.warpper.res.*;
import io.swagger.annotations.ApiOperation;
import org.apache.http.entity.ContentType;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
@@ -20,14 +31,25 @@
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.http.*;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.*;
import java.util.stream.Collectors;
/**
@@ -49,8 +71,58 @@
    private ICollectionHouseResourceService collectionHouseResourceService;
    @Resource
    private MongoTemplate mongoTemplate;
    @Autowired
    private IHousingDemandService housingDemandService;
    @Autowired
    private WxAppletTools wxAppletTools;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private OSSService ossService;
    @Value("${wx.appletsAppid}")
    private String wxAppletsAppid;
    @Value("${wx.appletsAppSecret}")
    private String wxAppletsAppSecret;
    /**
     * 生成小程序码地址
     */
    public static final String CREATE_CODE_URL = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=ACCESS_TOKEN";
    // 生成小程序码
    public String generateMiniProgramCode(String outputFilePath) throws IOException {
        // 获取access_token
        String accessToken = wxAppletTools.getAccessToken();
        // 替换CREATE_CODE_URL
        String uri = CREATE_CODE_URL.replace("ACCESS_TOKEN", accessToken);
        // 跳转到的小程序页面路径
        String pagePath = "pages/index/index";
        URL url = new URL(uri);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        // 设置请求方法
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        // 构建请求参数
        String params = "path=" + URLEncoder.encode(pagePath, "UTF-8");
        // 获取输出流
        try (OutputStream outputStream = connection.getOutputStream()) {
            outputStream.write(params.getBytes());
        }
        // 获取输入流
        try (InputStream inputStream = connection.getInputStream();
             FileOutputStream outputStream = new FileOutputStream(outputFilePath)) {
            // 将返回的图片数据写入文件
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(buffer);
            MultipartFile file = new MockMultipartFile(ContentType.APPLICATION_OCTET_STREAM.toString(), byteArrayInputStream);
            return ossService.uploadFile(file);
        }
    }
    /**
@@ -65,35 +137,55 @@
        if(req.getType() == 1){
            fillSearchHistory(req);
        }
        //区域
        List<Integer> districtIds = null;
        List<Integer> cityIds = null;
        if(StringUtils.hasLength(req.getDistrict())){
            cityIds = new ArrayList<>();
            districtIds = new ArrayList<>();
            JSONArray jsonArray = JSON.parseArray(req.getDistrict());
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                Integer cityId = jsonObject.getInteger("cityId");
                Integer districtId = jsonObject.getInteger("districtId");
                //不限区域
                if(0 == districtId || null == districtId){
                    List<Region> regions = regionService.selectList(new EntityWrapper<Region>().eq("parent_id", cityId));
                    districtIds.addAll(regions.stream().map(Region::getId).collect(Collectors.toList()));
        List<Integer> districtIds = new ArrayList<>();
        List<Integer> cityIds = new ArrayList<>();
        if (req.getDistrict() != null &&(!req.getDistrict().equals("")) ){
            // 一级id
            Integer integer = Integer.valueOf(req.getDistrict());
            districtIds.add(integer);
            if (req.getArea()!=null && (!req.getArea().equals(""))){
                String[] split = req.getArea().split(",");
                for (String s : split) {
                    cityIds.add(Integer.valueOf(s));
                }
                cityIds.add(cityId);
                districtIds.add(districtId);
            }
        }
//        if(StringUtils.hasLength(req.getDistrict())){
//            cityIds = new ArrayList<>();
//            districtIds = new ArrayList<>();
//            JSONArray jsonArray = JSON.parseArray(req.getDistrict());
//            for (int i = 0; i < jsonArray.size(); i++) {
//                JSONObject jsonObject = jsonArray.getJSONObject(i);
//                Integer cityId = jsonObject.getInteger("cityId");
//                Integer districtId = jsonObject.getInteger("districtId");
//                //不限区域
//                if(0 == districtId || null == districtId){
//                    List<Region> regions = regionService.selectList(new EntityWrapper<Region>().eq("parent_id", cityId));
//                    districtIds.addAll(regions.stream().map(Region::getId).collect(Collectors.toList()));
//                }
//                cityIds.add(cityId);
//                districtIds.add(districtId);
//            }
//        }
        //价格范围
        Double saleAmountStart = null;
        Double saleAmountEnd = null;
        if(StringUtils.hasLength(req.getSaleAmount())){
            String[] split = req.getSaleAmount().split("-");
            saleAmountStart = Double.valueOf(split[0]);
            saleAmountEnd = Double.valueOf(split[1]);
            if (req.getSaleAmount().contains("以上")){
                saleAmountStart = Double.valueOf(req.getSaleAmount().substring(0, req.getSaleAmount().length() - 2));
                saleAmountEnd = 10000000000000000000000.0;
            }else if (req.getSaleAmount().contains("以下")){
                saleAmountStart = 0.0;
                saleAmountEnd = Double.valueOf(req.getSaleAmount().substring(0, req.getSaleAmount().length() - 2));
            }else{
                String[] split = req.getSaleAmount().split("-");
                saleAmountStart = Double.valueOf(split[0]);
                saleAmountEnd = Double.valueOf(split[1]);
            }
        }
        //户型
        List<String> houseModels = null;
@@ -114,11 +206,9 @@
        SearchHouseResourceRes searchHouseResource = new SearchHouseResourceRes();
        List<SearchHouseResourceListRes> searchHouseResourceListRes = this.baseMapper.searchHouseResource(req, cityIds, districtIds, saleAmountStart, saleAmountEnd, houseModels, houseTypeIds);
        searchHouseResource.setList(searchHouseResourceListRes);
        Integer integer = this.baseMapper.searchHouseResourceCount(req, cityIds, districtIds, saleAmountStart, saleAmountEnd, houseModels, houseTypeIds);
        searchHouseResource.setTotal(integer);
        searchHouseResource.setTotal(searchHouseResourceListRes.size());
        return searchHouseResource;
    }
    /**
     * 填装历史搜索记录和修改历史搜索记录
@@ -128,7 +218,8 @@
        AppUser appUser = appUserService.getAppUser();
        if(null != appUser){
            //获取历史搜索数据
            SearchHistoryCondition searchHistoryCondition = searchHistoryConditionService.selectOne(new EntityWrapper<SearchHistoryCondition>().eq("app_user_id", appUser.getId()));
            SearchHistoryCondition searchHistoryCondition = searchHistoryConditionService
                    .selectOne(new EntityWrapper<SearchHistoryCondition>().eq("app_user_id", appUser.getId()));
            if(null == searchHistoryCondition){
                //没有历史记录,将现有记录添加进去
                searchHistoryCondition = new SearchHistoryCondition();
@@ -144,11 +235,11 @@
                if(ToolUtil.isEmpty(req.getDistrict()) && ToolUtil.isEmpty(req.getSaleAmount()) &&
                        ToolUtil.isEmpty(req.getHouseModel()) && ToolUtil.isEmpty(req.getElevator()) &&
                        ToolUtil.isEmpty(req.getHouseTypeId())){
                    req.setDistrict(searchHistoryCondition.getDistrict());
                    req.setSaleAmount(searchHistoryCondition.getPrice());
                    req.setHouseModel(searchHistoryCondition.getHouseModels());
                    req.setElevator(searchHistoryCondition.getElevator());
                    req.setHouseTypeId(searchHistoryCondition.getHouseTypeIds());
//                    req.setDistrict(searchHistoryCondition.getDistrict());
//                    req.setSaleAmount(searchHistoryCondition.getPrice());
//                    req.setHouseModel(searchHistoryCondition.getHouseModels());
//                    req.setElevator(searchHistoryCondition.getElevator());
//                    req.setHouseTypeId(searchHistoryCondition.getHouseTypeIds());
                }else{
                    //更新历史搜索记录
                    searchHistoryCondition.setDistrict(req.getDistrict());
@@ -181,19 +272,23 @@
     */
    @Override
    public HouseResourceInfoRes getHouseResourceInfo(Integer id) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        AppUser appUser = appUserService.getAppUser();
        HouseResource houseResource = this.selectById(id);
        HouseResourceInfoRes houseResourceInfoRes = new HouseResourceInfoRes();
        houseResourceInfoRes.setDataType(houseResource.getDataType());
        houseResourceInfoRes.setId(id);
        houseResourceInfoRes.setBuildingOrientation(houseResource.getBuildingOrientation());
        houseResourceInfoRes.setVideoPhoto(houseResource.getVideoPhoto());
        houseResourceInfoRes.setQrCode(houseResource.getQrCode());
        houseResourceInfoRes.setTitle(houseResource.getTitle());
        houseResourceInfoRes.setSaleAmount(houseResource.getSaleAmount());
        houseResourceInfoRes.setHouseModel(houseResource.getHouseModel());
        houseResourceInfoRes.setRentalDuration(houseResource.getRentalDuration());
        houseResourceInfoRes.setSaleDate(sdf.format(houseResource.getSaleDate()));
        houseResourceInfoRes.setSaleDate(houseResource.getStartTime());
        houseResourceInfoRes.setHousePhoto(houseResource.getHousePhoto());
        HouseType houseType = houseTypeService.selectById(houseResource.getHouseTypeId());
        houseResourceInfoRes.setHouseType(houseType.getName());
        if (houseType!=null)houseResourceInfoRes.setHouseType(houseType.getName());
        houseResourceInfoRes.setFloor(houseResource.getFloor());
        houseResourceInfoRes.setElevator(houseResource.getElevator());
        houseResourceInfoRes.setDryingArea(houseResource.getDryingArea());
@@ -201,7 +296,13 @@
        houseResourceInfoRes.setKeepPet(houseResource.getKeepPet());
        Region region = regionService.selectById(houseResource.getDistrictId());
        Region region1 = regionService.selectById(houseResource.getCityId());
        houseResourceInfoRes.setAddress(region1.getName() + " > " + region.getName() + "/" + houseResource.getHouseAddress());
        if (region != null&&region1 != null){
            if (houseResource.getHouseAddress()==null){
                houseResourceInfoRes.setAddress(region1.getName() + " > " + region.getName());
            }else{
                houseResourceInfoRes.setAddress(region1.getName() + " > " + region.getName() + "/" +houseResource.getHouseAddress() );
            }
        }
        houseResourceInfoRes.setLongitude(houseResource.getLongitude());
        houseResourceInfoRes.setLatitude(houseResource.getLatitude());
        houseResourceInfoRes.setMoreIntroduction(houseResource.getMoreIntroduction());
@@ -211,7 +312,9 @@
        houseResourceInfoRes.setNickname(appUser1.getNickname());
        houseResourceInfoRes.setUserType(appUser1.getUserType());
        houseResourceInfoRes.setInsertTime(sdf.format(houseResource.getInsertTime()));
        houseResourceInfoRes.setUpdateTime(sdf.format(houseResource.getUpdateTime()));
        if (houseResource.getUpdateTime()!=null){
            houseResourceInfoRes.setUpdateTime(sdf.format(houseResource.getUpdateTime()));
        }
        houseResourceInfoRes.setCode(houseResource.getCode());
        int collectionTimes = collectionHouseResourceService.selectCount(new EntityWrapper<CollectionHouseResource>().eq("house_resource_id", id));
        houseResourceInfoRes.setCollectionTimes(collectionTimes);
@@ -245,13 +348,15 @@
    public List<SearchHouseResourceListRes> getNearbyHouseResource(Integer id) {
        HouseResource houseResource = this.selectById(id);
        //获取中心半径5KM范围内的房源数据
        if (houseResource.getLongitude()!=null && houseResource.getLatitude()!=null){
        Double x = Double.valueOf(houseResource.getLongitude());
        Double y = Double.valueOf(houseResource.getLatitude());
        Point point = new Point(x, y);
        Circle circle = new Circle(point, new Distance(5, Metrics.KILOMETERS));
        Circle circle = new Circle(point, new Distance(100000, Metrics.KILOMETERS));
        Query query = Query.query(Criteria.where("geoJsonPoint").withinSphere(circle));
        List<PointLocation> pointLocations = mongoTemplate.find(query, PointLocation.class);
        List<Integer> ids = pointLocations.stream().map(PointLocation::getHouseId).collect(Collectors.toList());
        if (ids.size()!= 0){
        List<HouseResource> houseResources = this.selectBatchIds(ids);
        List<SearchHouseResourceListRes> list = new ArrayList<>();
        //遍历解析出返回数据
@@ -276,6 +381,11 @@
            searchHouseResourceListRes.setKeepPet(resource.getKeepPet());
            list.add(searchHouseResourceListRes);
        }
            return list;
        }
        }
        List<SearchHouseResourceListRes> list = new ArrayList<>();
        return list;
    }
@@ -295,6 +405,189 @@
        return contactInformationRes;
    }
    @Override
    public SearchHouseResourceRes listHouse(HouseQuery query) {
        SearchHouseResourceRes res = new SearchHouseResourceRes();
        res.setList(this.baseMapper.listHouse(query));
        res.setTotal(res.getList().size());
        return res;
    }
    @Override
    public ResultUtil addHouse(AddHouseReq req) {
        Integer appUserId = appUserService.getAppUser().getId();
        AppUser appUser = appUserService.selectOne(new EntityWrapper<AppUser>()
                .eq("id", appUserId)
                .eq("status", 1));
        if (appUser!=null){
            if (req.getId()==null){
                if (req.getType()!=1){
                if (appUser.getAuditStatus()!=2){
                    // 未认证 只能能发布三条房源信息
                    List<HouseResource> houseResources = this.selectList(new EntityWrapper<HouseResource>()
                            .eq("app_user_id", appUserId)
                            .eq("is_delete", 1)
                            .eq("status", 1)
                    );
                    if (houseResources.size()>=3){
                        return ResultUtil.error("中介账号未认证,只能同时上架3条房源信息");
                    }
                }else if (appUser.getAuditStatus()==2){
                    // 已经认证 只能能发布20条房源信息
                    List<HouseResource> houseResources = this.selectList(new EntityWrapper<HouseResource>()
                            .eq("app_user_id", appUserId)
                            .eq("is_delete", 1)
                            .eq("status", 1)
                    );
                    if (houseResources.size()>=20){
                        return ResultUtil.error("当前中介账号只能同时上架20条房源信息");
                    }
                }
                }
            }
            HouseResource houseResource = new HouseResource();
            houseResource.setPlatform(req.getPlatform());
            BeanUtils.copyProperties(req,houseResource);
            houseResource.setType(req.getType());
            houseResource.setInsertTime(new Date());
            houseResource.setGoodHouse(0);
            houseResource.setIsDelete(0);
            houseResource.setInsertUserId(appUserId);
            houseResource.setViewsNumber(0);
            // todo 修改回审核和上下架状态
            houseResource.setStatus(1);
            houseResource.setDataType(req.getDataType());
            houseResource.setAuthStatus(1);
            houseResource.setLeaseTime(req.getTime());
            houseResource.setAppUserId(appUserService.getAppUser().getId());
            houseResource.setFirmHouse(req.getFirmHouse());
            if (StringUtils.hasLength(req.getTime())){
                if (req.getTime().contains("年")){
                    houseResource.setRentalDuration(2);
                }else{
                    houseResource.setRentalDuration(1);
                }
            }
            if (req.getType()==2){
                InputStream inputStream = null;
                OutputStream outputStream = null;
                String accessToken = wxAppletTools.getAccessToken();
                try {
                    String url = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=" + accessToken;
                    Map<String, Object> param = new HashMap<>();
                    param.put("path", "pages/home/home");
//            param.put("page", "pages/index/index"); // 路径 如果没有默认跳转到首页面微信小程序发布后才可以使用不能添加参数
                    param.put("width", 200); //二维码尺寸
                    param.put("is_hyaline", true); // 是否需要透明底色, is_hyaline 为true时,生成透明底色的小程序码 参数仅对小程序码生效
                    param.put("auto_color", true); // 自动配置线条颜色,如果颜色依然是黑色,则说明不建议配置主色调 参数仅对小程序码生效
                    Map<String, Object> line_color = new HashMap<>();
                    line_color.put("r", 0);
                    line_color.put("g", 0);
                    line_color.put("b", 0);
                    param.put("line_color", line_color);
                    System.err.println("调用生成微信URL接口传参:" + param);
                    MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
                    HttpEntity requestEntity = new HttpEntity(param, headers);
                    ResponseEntity<byte[]> entity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
                    System.err.println("调用小程序生成微信永久小程序码URL接口返回结果:" + entity.getBody());
                    byte[] result = entity.getBody();
                    System.err.println(Base64.encodeBase64String(result));
                    inputStream = new ByteArrayInputStream(result);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                    // 最后上传生成的文件名
                    String finalFileName = System.currentTimeMillis() + "" + new SecureRandom().nextInt(0x0400) + ".jpg";
                    // oss中的文件夹名
                    String objectName = sdf.format(new Date()) + "/" + finalFileName;
                    // 上传oss
                    ossService.uploadFile2OSS(inputStream, objectName);
                    //获取文件的URl地址
                    String imgUrl = ossService.getImgUrl(objectName);
                    houseResource.setQrCode(imgUrl);
                    System.err.println("看看文件路径" + imgUrl);
                } catch (Exception e) {
                    System.err.println("调用小程序生成微信永久小程序码URL接口异常" + e);
                } finally {
                    if (inputStream != null) {
                        try {
                            inputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (outputStream != null) {
                        try {
                            outputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }
                }
                this.baseMapper.insert(houseResource);
            }else{
                if (req.getId()==null){
                    this.baseMapper.insert(houseResource);
                }else{
                    this.baseMapper.updateById(houseResource);
                }
            }
            return ResultUtil.success();
        }
        return ResultUtil.success();
    }
    @Override
    public ResultUtil confirm(Integer userType) {
        AppUser appUser = appUserService.getAppUser();
        appUser.setUserType(userType);
        appUserService.updateById(appUser);
        return ResultUtil.success();
    }
    @Override
    public List<CollectListRes> collect(Integer id) {
      return this.baseMapper.collect(id);
    }
    @Override
    public ResultUtil<Integer> getSurplusPushNumber1() {
        AppUser appUser = appUserService.getAppUser();
        // 判断这个人是什么身份
        if (appUser.getUserType()==2){
            // 最多只能发布三条房源信息
            int size = this.baseMapper.selectList(new EntityWrapper<HouseResource>()
                    .eq("app_user_id", appUser.getId())
                    .eq("is_delete", 1)
            ).size();
            if (3-size<0)size=0;
            return ResultUtil.success(3-size);
        }
        if (appUser.getUserType()==3){
            // 如果是中介 判断他是否认证成功
            if (appUser.getAuditStatus()==2){
                // 可以发布20条
                // 最多只能发布三条房源信息
                int size = this.baseMapper.selectList(new EntityWrapper<HouseResource>()
                        .eq("app_user_id", appUser.getId())
                        .eq("is_delete", 1)
                ).size();
                if (20-size<0)size=0;
                return ResultUtil.success(3-size);
            }else{
                int size = this.baseMapper.selectList(new EntityWrapper<HouseResource>()
                        .eq("app_user_id", appUser.getId())
                        .eq("is_delete", 1)
                ).size();
                if (3-size<0)size=0;
                return ResultUtil.success(3-size);
            }
        }
        return ResultUtil.success(0);
    }
    public List<CollectListRes> release(UserInfoQuery query, List<Integer> collect) {
        return this.baseMapper.release(query,collect);
    }
}