package com.huiju.estateagents.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huiju.estateagents.base.ResponseBean;
import com.huiju.estateagents.center.taUser.entity.TaUser;
import com.huiju.estateagents.center.taUser.mapper.TaUserMapper;
import com.huiju.estateagents.common.CommConstant;
import com.huiju.estateagents.common.StringUtils;
import com.huiju.estateagents.entity.*;
import com.huiju.estateagents.mapper.*;
import com.huiju.estateagents.service.*;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 项目表 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2019-05-10
 */
@Service
public class TaBuildingServiceImpl extends ServiceImpl<TaBuildingMapper, TaBuilding> implements ITaBuildingService {
    @Autowired
    TaBuildingMapper taBuildingMapper;

    @Autowired
    TaBuildingImgMapper taBuildingImgMapper;

    @Autowired
    TaBuildingTagMapper taBuildingTagMapper;

    @Autowired
    TaApartmentImgMapper taApartmentImgMapper;

    @Autowired
    TaBuildingApartmentMapper taBuildingApartmentMapper;

    @Autowired
    TaSaveMapper taSaveMapper;

    @Autowired
    TaUvMapper taUvMapper;

    @Autowired
    TaShareMapper taShareMapper;

    @Autowired
    TaPersonMapper taPersonMapper;

    @Autowired
    TaUserMapper taUserMapper;

    @Autowired
    TdCityMapper tdCityMapper;

    @Autowired
    private TaGoodsMapper taGoodsMapper;

    @Autowired
    private TaNewsMapper taNewsMapper;

    @Autowired
    private TaBuildingDynamicMapper taBuildingDynamicMapper;

    @Autowired
    private HelpActivityMapper helpActivityMapper;

    @Autowired
    private TaShareActivityMapper taShareActivityMapper;

    @Autowired
    private TaLiveActivityMapper taLiveActivityMapper;

    @Autowired
    private TaExtendContentMapper taExtendContentMapper;

    @Autowired
    private TaBuildingProjectTypeMapper taBuildingProjectTypeMapper;

    @Autowired
    private TaPosterService taPosterService;

    @Autowired
    private TaShareContentService taShareContentService;

    @Autowired
    private TaOrgMapper taOrgMapper;

    @Autowired
    private ITaBuildingMapRelationService iTaBuildingMapRelationService;

    @Autowired
    public ITaBuildingIntentionService iTaBuildingIntentionService;

    @Autowired
    private ITaBuildingPanoramaService taBuildingPanoramaService;

    @Autowired
    private ITaSalesBatchService iTaSalesBatchService;

    @Autowired
    private TaPersonBuildingMapper taPersonBuildingMapper;

    @Autowired
    private ITaRaiseService iTaRaiseService;

    @Autowired
    private ITaPersonService iTaPersonService;

    @Autowired
    private ITaRaiseInviteService iTaRaiseInviteService;

    @Autowired
    private IExtendContentService iExtendContentService;

    @Override
    public ResponseBean buildingList(Integer pageNum, Integer pageSize, String name, String code, LocalDateTime startDate, String buildingStatus, String marketStatus, Integer cityId, Integer isMain, Integer orgId, List<TaPersonBuilding> taPersonBuildingList) {
        Page<TaBuilding> page = new Page<>();
        page.setSize(pageSize == null ? 10 : pageSize);
        page.setCurrent(pageNum == null ? 1 : pageNum);

        List<TaBuilding> buildings = taBuildingMapper.buildingList(page, name, code, startDate, buildingStatus, marketStatus, cityId, isMain, orgId, taPersonBuildingList);

        if (null != buildings) {
            for (TaBuilding taBuilding : buildings) {
                //查询当前图片
                QueryWrapper<TaBuildingImg> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("building_id", taBuilding.getBuildingId());
                queryWrapper.eq("img_type", CommConstant.BUILDING_IMG_BANNER);
                queryWrapper.orderByAsc("create_date");

                List<TaBuildingImg> buildingImg = taBuildingImgMapper.selectList(queryWrapper);
                taBuilding.setBuildingImg(buildingImg);

                //查询封面当前图片
                QueryWrapper<TaBuildingImg> queryListWrapper = new QueryWrapper<>();
                queryListWrapper.eq("building_id", taBuilding.getBuildingId());
                queryListWrapper.eq("img_type", CommConstant.BUILDING_IMG_LIST);
                queryListWrapper.orderByAsc("create_date");

                List<TaBuildingImg> buildingListImg = taBuildingImgMapper.selectList(queryListWrapper);
                taBuilding.setBuildingListImg(buildingListImg);
            }
        }

        page.setRecords(buildings);

        return ResponseBean.success(page);
    }

    @Override
    public ResponseBean buildingListSelect(Integer pageNum, Integer pageSize, String name, String code, LocalDateTime startDate, String buildingStatus, String marketStatus, Integer cityId, Integer isMain, Integer orgId, List<TaPersonBuilding> taPersonBuildingList) {
//        Page<TaBuilding> page = new Page<>();
//        page.setSize(pageSize == null ? 10 : pageSize);
//        page.setCurrent(pageNum == null ? 1 : pageNum);
        List<TaBuilding> building = taBuildingMapper.buildingListSelect(name, code, startDate, buildingStatus, marketStatus, cityId, isMain, orgId, taPersonBuildingList);
//        page.setRecords(building);
        return ResponseBean.success(building);
    }

    /**
     * 查询项目图片
     *
     * @param buildingId
     * @param imgType
     * @return
     */
    private List<TaBuildingImg> getBuildingImg(String buildingId, String imgType) {
        //查询当前图片
        QueryWrapper<TaBuildingImg> buildingImgQueryWrapper = new QueryWrapper<>();
        buildingImgQueryWrapper.eq("building_id", buildingId);
        buildingImgQueryWrapper.eq("img_type", imgType);
        buildingImgQueryWrapper.orderByAsc("order_no");
        List<TaBuildingImg> buildingImg = taBuildingImgMapper.selectList(buildingImgQueryWrapper);
        return buildingImg.size() > 0 ? buildingImg : null;
    }

    @Override
    public ResponseBean buildingSelectId(String id) {
        // 查询基础信息
        QueryWrapper<TaBuilding> buildingtWrapper = new QueryWrapper<>();
        buildingtWrapper.lambda().gt(TaBuilding::getStatus, -1);
        buildingtWrapper.lambda().eq(TaBuilding::getBuildingId, id);
        TaBuilding building = taBuildingMapper.selectOne(buildingtWrapper);

        //查询当前图片
        building.setBuildingImg(getBuildingImg(id, CommConstant.BUILDING_IMG_BANNER));

        // 列表图
        building.setBuildingListImg(getBuildingImg(building.getBuildingId(), CommConstant.BUILDING_IMG_LIST));

        // 视频封面图
        building.setVideoImage(getBuildingImg(building.getBuildingId(), CommConstant.BUILDING_IMG_VIDEOIMAGE));

        // 查询tag
        QueryWrapper<TaBuildingTag> BuildingTagQueryWrapper = new QueryWrapper<>();
        BuildingTagQueryWrapper.eq("building_id", id);
        List<TaBuildingTag> buildingTags = taBuildingTagMapper.selectList(BuildingTagQueryWrapper);
        building.setBuildingTag(buildingTags);

        // 项目类型
        QueryWrapper<TaBuildingProjectType> buildingProjectTypeQueryWrapper = new QueryWrapper<>();
        buildingProjectTypeQueryWrapper.eq("building_id", building.getBuildingId());
        List<TaBuildingProjectType> taBuildingProjectTypes = taBuildingProjectTypeMapper.selectList(buildingProjectTypeQueryWrapper);
        building.setBuildingProjectType(taBuildingProjectTypes);
        building.setPosters(taPosterService.getPostersForTarget(id, CommConstant.POSTER_CONTENT_TYPE_BUILDING));
        building.setShareContents(taShareContentService.getPostersForTarget(id, CommConstant.POSTER_CONTENT_TYPE_BUILDING));

        // 查询 周边数据
        QueryWrapper<TaBuildingMapRelation> mapRelationQueryWrapper = new QueryWrapper<>();
        mapRelationQueryWrapper.eq("building_id", building.getBuildingId());
        mapRelationQueryWrapper.eq("org_id", building.getOrgId());
        List<TaBuildingMapRelation> mapRelationList = iTaBuildingMapRelationService.list(mapRelationQueryWrapper);
        building.setMapJson(mapRelationList.size() > 0 ? JSONObject.toJSONString(mapRelationList) : null);

        return ResponseBean.success(building);
    }

    @Override
    public ResponseBean      buildingAllSelectId(String id, TaPerson person, Integer orgId) {
        // 查询基础信息
        QueryWrapper<TaBuilding> buildingtWrapper = new QueryWrapper<>();
        buildingtWrapper.lambda().gt(TaBuilding::getStatus, -1);
        buildingtWrapper.lambda().eq(TaBuilding::getBuildingId, id);
        TaBuilding building = taBuildingMapper.selectOne(buildingtWrapper);

        if (null == building) {
            return ResponseBean.error("项目不存在", ResponseBean.ERROR_UNAVAILABLE);
        }

        if (1 != building.getStatus()) {
            return ResponseBean.error("项目未发布", ResponseBean.ERROR_UNAVAILABLE);
        }

        //查询当前图片
        building.setBuildingImg(getBuildingImg(id, CommConstant.BUILDING_IMG_BANNER));

        // 视频封面图
        building.setVideoImage(getBuildingImg(building.getBuildingId(), CommConstant.BUILDING_IMG_VIDEOIMAGE));

        // 查询tag
        QueryWrapper<TaBuildingTag> BuildingTagQueryWrapper = new QueryWrapper<>();
        BuildingTagQueryWrapper.eq("building_id", id);
        List<TaBuildingTag> buildingTags = taBuildingTagMapper.selectList(BuildingTagQueryWrapper);
        building.setBuildingTag(buildingTags);

//        QueryWrapper<Visit> BuildingVisitQueryWrapper = new QueryWrapper<>();
//        BuildingVisitQueryWrapper.eq("visit_type", "building");
//        BuildingVisitQueryWrapper.eq("visit_content", id);
//        BuildingVisitQueryWrapper.orderByDesc("visit_date");
//        List<Visit> visits = visitMapper.selectList(BuildingVisitQueryWrapper);
//        building.setVisits(visits);

        // 查询户型
        QueryWrapper<TaBuildingApartment> AppointmentQueryWrapper = new QueryWrapper<>();
        AppointmentQueryWrapper.eq("building_id", id);
        AppointmentQueryWrapper.eq("status", 1);
        AppointmentQueryWrapper.orderByDesc("order_no");
        AppointmentQueryWrapper.orderByDesc("create_date");
        List<TaBuildingApartment> appoint = taBuildingApartmentMapper.selectList(AppointmentQueryWrapper);
        for (TaBuildingApartment apar : appoint) {
            List<TaBuildingImg> imgs = taBuildingImgMapper.getBuildingImgByApartment(apar.getApartmentId());
            apar.setBuildingImgList(imgs);
        }
        building.setBuildingApartment(appoint);

        getBuildingAttaches(building);
        QueryWrapper<TaSave> saveQueryWrapper = new QueryWrapper<>();
        saveQueryWrapper.eq("tagert_type", CommConstant.FAVOR_PROJECT);
        saveQueryWrapper.eq("person_id", person.getPersonId());
        saveQueryWrapper.eq("saved_target", building.getBuildingId());
        Integer num = taSaveMapper.selectCount(saveQueryWrapper);
        if (num > 0) {
            building.setIsSave(CommConstant.STATUS_NORMAL);
        } else {
            building.setIsSave(CommConstant.STATUS_UNACCALIMED);
        }

        // 项目类型
        QueryWrapper<TaBuildingProjectType> projectTypeQueryWrapper = new QueryWrapper<>();
        projectTypeQueryWrapper.eq("building_id", building.getBuildingId());
        projectTypeQueryWrapper.eq("status", 1);
        List<TaBuildingProjectType> buildingProjectTypes = taBuildingProjectTypeMapper.selectList(projectTypeQueryWrapper);
        building.setBuildingProjectType(buildingProjectTypes);

        // 海报和分享
        building.setPosters(taPosterService.getPostersForTarget(id, CommConstant.POSTER_CONTENT_TYPE_BUILDING));
        building.setShareContents(taShareContentService.getPostersForTarget(id, CommConstant.POSTER_CONTENT_TYPE_BUILDING));

        // 助力活动
        QueryWrapper<HelpActivity> helpActivityQueryWrapper = new QueryWrapper<>();
        helpActivityQueryWrapper.eq("building_id", id);
        helpActivityQueryWrapper.eq("status", 1);
        helpActivityQueryWrapper.in("activity_status", 0, 1);
        List<HelpActivity> helpActivityList = helpActivityMapper.selectList(helpActivityQueryWrapper);

        building.setHelpActivityList(helpActivityList);

        // 拼团活动
        QueryWrapper<TaShareActivity> shareActivityQueryWrapper = new QueryWrapper<>();
        shareActivityQueryWrapper.eq("building_id", id);
        shareActivityQueryWrapper.eq("status", 1);
        shareActivityQueryWrapper.in("activity_status", 0, 1);
        List<TaShareActivity> shareActivityList = taShareActivityMapper.selectList(shareActivityQueryWrapper);
        building.setShareActivityList(shareActivityList);

        // 直播活动
        QueryWrapper<TaLiveActivity> liveActivityQueryWrapper = new QueryWrapper<>();
        liveActivityQueryWrapper.eq("building_id", id);
        liveActivityQueryWrapper.eq("status", 1);
        List<TaLiveActivity> liveActivityList = taLiveActivityMapper.selectList(liveActivityQueryWrapper);
        building.setLiveActivityList(liveActivityList);

        // 查询 周边数据
        QueryWrapper<TaBuildingMapRelation> mapRelationQueryWrapper = new QueryWrapper<>();
        mapRelationQueryWrapper.eq("building_id", building.getBuildingId());
        mapRelationQueryWrapper.eq("org_id", building.getOrgId());
        List<TaBuildingMapRelation> mapRelationList = iTaBuildingMapRelationService.list(mapRelationQueryWrapper);
        building.setMapJson(mapRelationList.size() > 0 ? JSONObject.toJSONString(mapRelationList) : null);

        //查询关联的全景图列表
        QueryWrapper<TaBuildingPanorama> panoramaQueryWrapper = new QueryWrapper<>();
        panoramaQueryWrapper.eq("building_id", building.getBuildingId());
        panoramaQueryWrapper.eq("org_id", building.getOrgId());
        panoramaQueryWrapper.eq("status", CommConstant.STATUS_NORMAL);
        panoramaQueryWrapper.orderByDesc("create_date");
        List<TaBuildingPanorama> panoramaList = taBuildingPanoramaService.list(panoramaQueryWrapper);
        building.setPanoramaList(panoramaList);

        // 查询关联的销售批次
        QueryWrapper<TaSalesBatch> salesBatchQueryWrapper = new QueryWrapper<>();
        salesBatchQueryWrapper.lambda().eq(TaSalesBatch::getBuildingId, id);
        salesBatchQueryWrapper.lambda().eq(TaSalesBatch::getStatus, CommConstant.STATUS_NORMAL);
        List<TaSalesBatch> taSalesBatch = iTaSalesBatchService.list(salesBatchQueryWrapper);

        // 查询关联项目的开屏广告
        QueryWrapper<ExtendContent> taExtendContentQueryWrapper = new QueryWrapper<>();
        taExtendContentQueryWrapper.eq("status", CommConstant.STATUS_NORMAL);
        taExtendContentQueryWrapper.eq("building_id", id);
        taExtendContentQueryWrapper.eq("org_id", orgId);
        taExtendContentQueryWrapper.eq("show_type", CommConstant.OPEN_SCREEN);
        taExtendContentQueryWrapper.eq("show_position", CommConstant.BANNER_BUILDING);
        List<ExtendContent> taExtendContents = iExtendContentService.list(taExtendContentQueryWrapper);
        building.setExtendContent(taExtendContents);


        List<TaSalesBatch> resultSalesBatchList = new ArrayList<>();
        taSalesBatch.stream().forEach(record -> {
            // 查询批次下认筹是否开启邀请制
            QueryWrapper<TaRaise> taRaiseQueryWrapper = new QueryWrapper<>();
            taRaiseQueryWrapper.eq("org_id", orgId);
            taRaiseQueryWrapper.eq("sales_batch_id", record.getSalesBatchId());
            taRaiseQueryWrapper.eq("status", CommConstant.STATUS_NORMAL);
            TaRaise taRaise = iTaRaiseService.getOne(taRaiseQueryWrapper);
            if (taRaise == null) {
                resultSalesBatchList.add(record);
                return;
            }

            // 未开启邀请制
            if (CommConstant.STATUS_NORMAL != taRaise.getInvite()) {
                resultSalesBatchList.add(record);
                return;
            }

            if (CommConstant.STATUS_NORMAL == taRaise.getInvite()) {
                // 若开启邀请制，校验该用户是否在邀请列表中
                QueryWrapper<TaRaiseInvite> taRaiseInviteQueryWrapper = new QueryWrapper<>();
                taRaiseInviteQueryWrapper.eq("org_id", orgId);
                taRaiseInviteQueryWrapper.eq("invite_tel", person.getPhone());
                taRaiseInviteQueryWrapper.eq("sales_batch_id", record.getSalesBatchId());
                TaRaiseInvite taRaiseInvite = iTaRaiseInviteService.getOne(taRaiseInviteQueryWrapper);
                if (taRaiseInvite != null) {
                    resultSalesBatchList.add(record);
                }
            }
        });

        building.setSalesBatch(resultSalesBatchList);
        return ResponseBean.success(building);
    }

    @Override
    public ResponseBean buildingUpdate(String parameter, Integer orgId) {
        ResponseBean responseBean = new ResponseBean();
        JSONObject object = JSONObject.parseObject(parameter);

        TaBuilding building = object.toJavaObject(TaBuilding.class);

        boolean isMainMoreThanTenFlag = publishCountIsMainBuilding(building, orgId, null, "update");
        if (!isMainMoreThanTenFlag) {
            responseBean.addError("当前城市最多只能推荐10个项目至首页哦。");
            return responseBean;
        }

        // 先删除视频
        UpdateWrapper<TaBuilding> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("building_id", building.getBuildingId());
        updateWrapper.set("video_url", null);
        this.update(updateWrapper);

        //图片先删除再添加
        String imgStr = object.getString("img");
        List<TaBuildingImg> buildingImgs = JSONObject.parseArray(imgStr, TaBuildingImg.class);
        if (CollectionUtils.isNotEmpty(buildingImgs)) {
            QueryWrapper<TaBuilding> buildingIdQueryWrapper = new QueryWrapper<>();
            buildingIdQueryWrapper.eq("building_id", building.getBuildingId());
            buildingIdQueryWrapper.eq("org_id", orgId);
            building.setName(building.getBuildingName());
            taBuildingMapper.update(building, buildingIdQueryWrapper);
            QueryWrapper<TaBuildingImg> BuildingImgQueryWrapper = new QueryWrapper<>();
            BuildingImgQueryWrapper.eq("building_id", building.getBuildingId());
            BuildingImgQueryWrapper.eq("img_type", CommConstant.BUILDING_IMG_BANNER);
            taBuildingImgMapper.delete(BuildingImgQueryWrapper);
            insertImgBatch(buildingImgs, building.getBuildingId());
        }

        // 列表图
        String listImg = object.getString("listImg");
        List<TaBuildingImg> buildingListImg = JSONObject.parseArray(listImg, TaBuildingImg.class);
        if (CollectionUtils.isNotEmpty(buildingListImg)) {
            QueryWrapper<TaBuildingImg> BuildingListImgQueryWrapper = new QueryWrapper<>();
            BuildingListImgQueryWrapper.eq("building_id", building.getBuildingId());
            BuildingListImgQueryWrapper.eq("img_type", CommConstant.BUILDING_IMG_LIST);
            taBuildingImgMapper.delete(BuildingListImgQueryWrapper);
            buildingListImg = insertImgBatch(buildingListImg, building.getBuildingId());
        }

        // 视频封面图
        String videoImage = object.getString("videoImage");
        List<TaBuildingImg> videoImageList = JSONObject.parseArray(videoImage, TaBuildingImg.class);
        if (CollectionUtils.isNotEmpty(videoImageList)) {
            QueryWrapper<TaBuildingImg> BuildingListImgQueryWrapper = new QueryWrapper<>();
            BuildingListImgQueryWrapper.eq("building_id", building.getBuildingId());
            BuildingListImgQueryWrapper.eq("img_type", CommConstant.BUILDING_IMG_VIDEOIMAGE);
            taBuildingImgMapper.delete(BuildingListImgQueryWrapper);
            videoImageList = insertImgBatch(videoImageList, building.getBuildingId());
        }


        // tag先删除再增加
        String tagStr = object.getString("tag");
        List<TaBuildingTag> buildingTags = JSONObject.parseArray(tagStr, TaBuildingTag.class);
        if (CollectionUtils.isNotEmpty(buildingTags)) {
            QueryWrapper<TaBuildingTag> BuildingTagQueryWrapper = new QueryWrapper<>();
            BuildingTagQueryWrapper.eq("building_id", building.getBuildingId());
            taBuildingTagMapper.delete(BuildingTagQueryWrapper);
            insertTagBatch(buildingTags, building.getBuildingId());
        }

        if (null != building.getCityId()) {
            TdCity city = tdCityMapper.selectById(building.getCityId());
            city.setStatus("1");
            tdCityMapper.updateById(city);

            //更新商品城市
            TaGoods taGoods = new TaGoods();
            taGoods.setCityId(building.getCityId());
            QueryWrapper<TaGoods> goodsQueryWrapper = new QueryWrapper<>();
            goodsQueryWrapper.eq("building_id", building.getBuildingId());
            taGoodsMapper.update(taGoods, goodsQueryWrapper);

            //更新资讯城市
            TaNews taNews = new TaNews();
            taNews.setCityId(building.getCityId());
            QueryWrapper<TaNews> newsQueryWrapper = new QueryWrapper<>();
            newsQueryWrapper.eq("building_id", building.getBuildingId());
            taNewsMapper.update(taNews, newsQueryWrapper);

            //更新活动城市
            TaBuildingDynamic taBuildingDynamic = new TaBuildingDynamic();
            taBuildingDynamic.setCityId(building.getCityId());
            QueryWrapper<TaBuildingDynamic> taBuildingDynamicQueryWrapper = new QueryWrapper<>();
            taBuildingDynamicQueryWrapper.eq("building_id", building.getBuildingId());
            taBuildingDynamicMapper.update(taBuildingDynamic, taBuildingDynamicQueryWrapper);

            //更新助力城市
            HelpActivity helpActivity = new HelpActivity();
            helpActivity.setCityId(building.getCityId());
            QueryWrapper<HelpActivity> helpActivityQueryWrapper = new QueryWrapper<>();
            helpActivityQueryWrapper.eq("building_id", building.getBuildingId());
            helpActivityMapper.update(helpActivity, helpActivityQueryWrapper);

            //更新拼团城市
            TaShareActivity taShareActivity = new TaShareActivity();
            taShareActivity.setCityId(building.getCityId());
            QueryWrapper<TaShareActivity> taShareActivityQueryWrapper = new QueryWrapper<>();
            taShareActivityQueryWrapper.eq("building_id", building.getBuildingId());
            taShareActivityMapper.update(taShareActivity, taShareActivityQueryWrapper);

            //更新直播城市
            TaLiveActivity taLiveActivity = new TaLiveActivity();
            taLiveActivity.setCityId(building.getCityId());
            taLiveActivity.setBuildingId(building.getBuildingId());
            QueryWrapper<TaLiveActivity> taLiveActivityQueryWrapper = new QueryWrapper<>();
            taLiveActivityQueryWrapper.eq("building_id", building.getBuildingId());
            taLiveActivityMapper.update(taLiveActivity, taLiveActivityQueryWrapper);

            //更新首页轮播、开屏广告、宣传位
            TaExtendContent taExtendContent = new TaExtendContent();
            taExtendContent.setCityId(building.getCityId());
            QueryWrapper<TaExtendContent> taExtendContentQueryWrapper = new QueryWrapper<>();
            taExtendContentQueryWrapper.eq("building_id", building.getBuildingId());
            taExtendContentMapper.update(taExtendContent, taExtendContentQueryWrapper);
        }

        // 项目类型
        // 先删除之前关联的
        taBuildingProjectTypeMapper.deleteByBuildingId(building.getBuildingId());
        JSONArray buildingProjectTypeArray = object.getJSONArray("buildingProjectType");
        if (CollectionUtils.isNotEmpty(buildingProjectTypeArray)) {
            taBuildingProjectTypeMapper.insertBuildingProjectTypeBatch(buildingProjectTypeArray, building.getBuildingId());
        }

        // 地图周边
        JSONArray mapJson = object.getJSONArray("mapJson");
        if (null != mapJson) {
            // 先删除
            QueryWrapper<TaBuildingMapRelation> mapRelationQueryWrapper = new QueryWrapper<>();
            mapRelationQueryWrapper.eq("building_id", building.getBuildingId());
            mapRelationQueryWrapper.eq("org_id", orgId);
            iTaBuildingMapRelationService.remove(mapRelationQueryWrapper);

            List<TaBuildingMapRelation> taBuildingMapRelations = mapJson.toJavaList(TaBuildingMapRelation.class);
            insertBuildingMapRelationBeach(taBuildingMapRelations, building.getBuildingId(), orgId);
        }

        return ResponseBean.success(building);
    }

    @Override
    public ResponseBean appointmentList(Integer pageNum, Integer pageSize, String buildingId, String username, String phone, String status) {
        return null;
    }

    @Override
    public ResponseBean buildingAdd(String parameter, Integer orgId, Integer userId) {
        ResponseBean responseBean = new ResponseBean();

        JSONObject object = JSONObject.parseObject(parameter);
        // 根据orgId查询当前楼盘最大数
        TaOrg taOrg = taOrgMapper.selectById(orgId);
        // 查询当前org楼盘总数
        QueryWrapper<TaBuilding> taBuildingQuery = new QueryWrapper<>();
        taBuildingQuery.eq("org_id", orgId);
        taBuildingQuery.gt("status", -1);
        int orgNum = taBuildingMapper.selectCount(taBuildingQuery);
        if (orgNum >= taOrg.getBuildingNum()) {
            return ResponseBean.error("当前系统仅供维护" + taOrg.getBuildingNum() + "个项目，需要维护更多项目，请联系相关管理人员", ResponseBean.ERROR_UNAVAILABLE);
        }

        TaBuilding building = object.toJavaObject(TaBuilding.class);

        boolean isMainMoreThanTenFlag = publishCountIsMainBuilding(building, orgId, null, "add");
        if (!isMainMoreThanTenFlag) {
            responseBean.addError("当前城市最多只能推荐10个项目至首页哦。");
            return responseBean;
        }

        building.setCreateDate(LocalDateTime.now());
        building.setStatus(2);
        building.setOrgId(orgId);
        building.setName(building.getBuildingName());
        if (taBuildingMapper.insert(building) < 1) {
            return ResponseBean.error("添加项目楼栋失败", ResponseBean.ERROR_UNAVAILABLE);
        }
        if (null != building.getCityId()) {
            TdCity city = tdCityMapper.selectById(building.getCityId());
            city.setStatus("1");
            tdCityMapper.updateById(city);
        }

        //新建项目以后自动授权给当前用户
        TaUser taUser = taUserMapper.selectById(userId);
        TaPersonBuilding taPersonBuilding = new TaPersonBuilding();
        taPersonBuilding.setBuildingId(building.getBuildingId());
        taPersonBuilding.setUserId(taUser.getUserId());
        taPersonBuilding.setCreateDate(LocalDateTime.now());
        taPersonBuildingMapper.insert(taPersonBuilding);

        // 项目主图
        String imgStr = object.getString("img");
        List<TaBuildingImg> buildingImgs = JSONObject.parseArray(imgStr, TaBuildingImg.class);
        if (CollectionUtils.isNotEmpty(buildingImgs)) {
            buildingImgs = insertImgBatch(buildingImgs, building.getBuildingId());
        }

        // 视频封面图
        String videoImage = object.getString("videoImage");
        List<TaBuildingImg> videoImageList = JSONObject.parseArray(videoImage, TaBuildingImg.class);
        if (CollectionUtils.isNotEmpty(videoImageList)) {
            videoImageList = insertImgBatch(videoImageList, building.getBuildingId());
        }

        // 列表图
        String listImg = object.getString("listImg");
        List<TaBuildingImg> buildingListImg = JSONObject.parseArray(listImg, TaBuildingImg.class);
        if (CollectionUtils.isNotEmpty(buildingListImg)) {
            buildingListImg = insertImgBatch(buildingListImg, building.getBuildingId());
        }

        // 标签
        String tagStr = object.getString("tag");
        List<TaBuildingTag> buildingTags = JSONObject.parseArray(tagStr, TaBuildingTag.class);
        if (CollectionUtils.isNotEmpty(buildingTags)) {
            buildingTags = insertTagBatch(buildingTags, building.getBuildingId());
        }

        // 项目类型
        JSONArray buildingProjectTypeArray = object.getJSONArray("buildingProjectType");
        if (CollectionUtils.isNotEmpty(buildingProjectTypeArray)) {
            taBuildingProjectTypeMapper.insertBuildingProjectTypeBatch(buildingProjectTypeArray, building.getBuildingId());
        }

        // 地图周边
        JSONArray mapJson = object.getJSONArray("mapJson");
        if (null != mapJson) {
            List<TaBuildingMapRelation> taBuildingMapRelations = mapJson.toJavaList(TaBuildingMapRelation.class);
            insertBuildingMapRelationBeach(taBuildingMapRelations, building.getBuildingId(), orgId);
        }

        //添加默认意向值
        iTaBuildingIntentionService.saveDefaultIntention(building.getOrgId(), building.getBuildingId());

        return ResponseBean.success(building);
    }

    /**
     * 批量插入 周边地图数据
     *
     * @param list
     * @param buildingId
     * @param orgId
     * @return
     */
    private List<TaBuildingMapRelation> insertBuildingMapRelationBeach(List<TaBuildingMapRelation> list, String buildingId, Integer orgId) {
        List<TaBuildingMapRelation> newList = list.stream().map(e -> {
            e.setBuildingId(buildingId);
            e.setOrgId(orgId);
            e.setStatus(1);
            e.setCreateDate(LocalDateTime.now());
            return e;
        }).collect(Collectors.toList());

        iTaBuildingMapRelationService.saveBatch(newList);
        return newList;
    }

    @Override
    public ResponseBean buildingUpdateStatus(String parameter, Integer orgId) {
        ResponseBean responseBean = new ResponseBean();

        JSONObject jsonobject = JSONObject.parseObject(parameter);
        Integer status = jsonobject.getInteger("status");
        String id = jsonobject.getString("id");
        QueryWrapper<TaBuilding> buildingIdQueryWrapper = new QueryWrapper<>();
        buildingIdQueryWrapper.eq("building_id", id);
        buildingIdQueryWrapper.eq("org_id", orgId);
        TaBuilding building = taBuildingMapper.selectOne(buildingIdQueryWrapper);

        boolean isMainMoreThanTenFlag = publishCountIsMainBuilding(building, orgId, status, "updateStatus");
        if (!isMainMoreThanTenFlag) {
            responseBean.addError("当前城市最多只能推荐10个项目至首页哦");
            return responseBean;
        }
        building.setStatus(status);
        taBuildingMapper.update(building, buildingIdQueryWrapper);
        return ResponseBean.success("");
    }

    @Override
    public ResponseBean buildingdelete(String id, Integer orgId) {
        TaBuilding building = new TaBuilding();
        QueryWrapper<TaBuilding> buildingtWrapper = new QueryWrapper<>();
        buildingtWrapper.lambda().eq(TaBuilding::getBuildingId, id);
        TaBuilding bui = taBuildingMapper.selectOne(buildingtWrapper);

        if (bui.getStatus().equals(1)) {
            return ResponseBean.error("楼盘已发布不可以删除", ResponseBean.ERROR_UNAVAILABLE);
        }
        QueryWrapper<TaBuilding> buildingIdQueryWrapper = new QueryWrapper<>();
        buildingIdQueryWrapper.eq("building_id", id);
        buildingIdQueryWrapper.eq("org_id", orgId);
        building.setBuildingId(String.valueOf(id));
        building.setStatus(-1);
        taBuildingMapper.update(building, buildingIdQueryWrapper);

        TaLiveActivity taLiveActivity = new TaLiveActivity();
        QueryWrapper<TaLiveActivity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("building_id", id);
        taLiveActivity.setStatus(0);
        taLiveActivity.setCityId(null);
        taLiveActivity.setBuildingId(null);
        taLiveActivityMapper.update(taLiveActivity, queryWrapper);
        return ResponseBean.success("");
    }

    @Override
    public ResponseBean buildingApartmentAdd(String parameter) {
        TaBuildingApartment building = JSONObject.parseObject(parameter, TaBuildingApartment.class);
        building.setStatus(1);
        building.setCreateDate(LocalDateTime.now());
        if (taBuildingApartmentMapper.insert(building) < 1) {
            return ResponseBean.error("新增楼盘户型失败", ResponseBean.ERROR_UNAVAILABLE);
        }

        JSONObject jsonobject = JSONObject.parseObject(parameter);

        //图片数组
        String imgStr = jsonobject.getString("img");
        //转集合
        List<TaBuildingImg> buildingImgs = JSONObject.parseArray(imgStr, TaBuildingImg.class);
        //插入户型图片
        insertApartmentImgBatch(buildingImgs, building.getBuildingId(), building.getApartmentId());

        return ResponseBean.success("");
    }

    @Override
    public ResponseBean buildingApartmentUpdate(String parameter) {
        ResponseBean responseBean = new ResponseBean();
        TaBuildingApartment building = JSONObject.parseObject(parameter, TaBuildingApartment.class);
        if (StringUtils.isEmpty(building.getApartmentId())) {
            responseBean.addError("id不存在!");
            return responseBean;
        }
        taBuildingImgMapper.delBuildingImgByApartment(building.getApartmentId());

        //删除户户型对应图片表
        QueryWrapper<TaApartmentImg> apartmentImgQueryWrapper = new QueryWrapper<>();
        apartmentImgQueryWrapper.eq("apartment_id", building.getApartmentId());
        taApartmentImgMapper.delete(apartmentImgQueryWrapper);

        QueryWrapper<TaBuildingApartment> buildingApartmentQueryWrapper = new QueryWrapper<>();
        buildingApartmentQueryWrapper.eq("apartment_id", building.getApartmentId());
        building.setInsideArea(building.getInsideArea() == null ? 0d : building.getInsideArea());
        building.setBuildingArea(building.getBuildingArea() == null ? 0d : building.getBuildingArea());
        taBuildingApartmentMapper.update(building, buildingApartmentQueryWrapper);

        JSONObject jsonobject = JSONObject.parseObject(parameter);
        //图片数组
        String imgStr = jsonobject.getString("img");
        //转集合
        List<TaBuildingImg> buildingImgs = JSONObject.parseArray(imgStr, TaBuildingImg.class);
        //插入户型图片删除之前的图片
        insertApartmentImgBatch(buildingImgs, building.getBuildingId(), building.getApartmentId());

        return ResponseBean.success("");
    }

    @Override
    public ResponseBean buildingApartmentSelectId(String id) {
        //查询户型详情
        QueryWrapper<TaBuildingApartment> buildingApartmentQueryWrapper = new QueryWrapper<>();
        buildingApartmentQueryWrapper.eq("apartment_id", id);
        //拿到当前户型信息
        TaBuildingApartment buildingApartment = taBuildingApartmentMapper.selectOne(buildingApartmentQueryWrapper);
        if (null == buildingApartment) {
            return ResponseBean.success("", "没有发现户型图上传");
        }

        //根据户型ID查楼盘户型对应图片表
        ArrayList arrayList = new ArrayList<>();
        QueryWrapper<TaApartmentImg> ApartmentImgQueryWrapper = new QueryWrapper<>();
        ApartmentImgQueryWrapper.eq("apartment_id", buildingApartment.getApartmentId());
        List<TaApartmentImg> buildingImg = taApartmentImgMapper.selectList(ApartmentImgQueryWrapper);
        for (TaApartmentImg apartmentImg : buildingImg) {
            QueryWrapper<TaBuildingImg> buildingImgQueryWrapper = new QueryWrapper<>();
            buildingImgQueryWrapper.eq("img_id", apartmentImg.getImgId());
            buildingImgQueryWrapper.eq("img_type", CommConstant.BUILDING_IMG_APARMENT);
            List<TaBuildingImg> buildingImgList = taBuildingImgMapper.selectList(buildingImgQueryWrapper);
            for (TaBuildingImg buImg : buildingImgList) {
                arrayList.add(buImg);
            }
        }
        buildingApartment.setBuildingImgList(arrayList);
        return ResponseBean.success(buildingApartment);
    }

    @Override
    public ResponseBean appointmentUpdate(String id, String writeoffRemark) {
        return null;
    }

    @Override
    public ResponseBean getWxBuildingList(
            Integer pageNum,
            Integer pageSize,
            String name,
            List<String> targets,
            Integer cityId,
            boolean mine,
            String[] houseTypeList,
            String[] buildingTypeList,
            List<String[]> priceList,
            List<String[]> areaList,
            Integer orgId, String priceType) {
        IPage<TaBuilding> page = new Page<>(pageNum, pageSize);

        if (CollectionUtils.isEmpty(targets) && mine) {
            return ResponseBean.success(page);
        }

//        QueryWrapper<TaBuilding> buildingQueryWrapper = new QueryWrapper<>();
//        buildingQueryWrapper.nested(null != name && !"".equals(name.trim()), i -> i.like("name", name).or().like("building_name", name));
//        buildingQueryWrapper.eq("status", 1);
//        buildingQueryWrapper.eq(null != cityId && cityId != 0,"city_id", cityId);
//        buildingQueryWrapper.in(null != targets && targets.size() > 0, "building_id", targets);
////        buildingQueryWrapper.like(null != name && !"".equals(name.trim()), "name", name);
//        buildingQueryWrapper.orderByAsc("order_no");
//        buildingQueryWrapper.eq(null != buildingTypeId,"building_type", buildingTypeId);
//
//        IPage<TaBuilding> result = taBuildingMapper.selectPage(page, buildingQueryWrapper);

        IPage<TaBuilding> result = taBuildingMapper.selectBuildingPage(page, name, cityId, targets, houseTypeList, buildingTypeList, priceList, areaList, orgId, priceType);

        List<TaBuilding> buildingList = result.getRecords();
        if (CollectionUtils.isNotEmpty(buildingList)) {
            for (TaBuilding build : buildingList) {
                getBuildingAttaches(build);

                // 兼容 3.0/3.5 版本（3.0/3.5 封面取的全是 buildingListImg 的第一张），因为在3.5.1新增了封面图

                // 获取封面图
                List<TaBuildingImg> buildingListImg = build.getBuildingListImg();
                if (CollectionUtils.isNotEmpty(buildingListImg)) {
                    // 把封面图写入到 BuildingImg 的第一张
                    if (CollectionUtils.isNotEmpty(build.getBuildingImg())) {
                        build.getBuildingImg().add(0, buildingListImg.get(0));
                    }
                }
            }
        }

        return ResponseBean.success(result);
    }

    private void getBuildingAttaches(TaBuilding build) {
        build.setBuildingImg(getBuildingImg(build.getBuildingId(), CommConstant.BUILDING_IMG_BANNER));
        build.setBuildingListImg(getBuildingImg(build.getBuildingId(), CommConstant.BUILDING_IMG_LIST));
        build.setVideoImage(getBuildingImg(build.getBuildingId(), CommConstant.BUILDING_IMG_VIDEOIMAGE));

//            QueryWrapper<Visit> BuildingVisitQueryWrapper = new QueryWrapper<>();
//            BuildingVisitQueryWrapper.eq("visit_type", "building");
//            BuildingVisitQueryWrapper.eq("visit_content", build.getBuildingId());
//            BuildingVisitQueryWrapper.orderByDesc("visit_date");
//            List<Visit> visits = visitMapper.selectList(BuildingVisitQueryWrapper);
//            build.setVisits(visits);

        QueryWrapper<TaBuildingTag> buildingTagQueryWrapper = new QueryWrapper<>();
        buildingTagQueryWrapper.eq("building_id", build.getBuildingId());
        List<TaBuildingTag> buildingTags = taBuildingTagMapper.selectList(buildingTagQueryWrapper);
        build.setBuildingTag(buildingTags);

        IPage<TaUv> page = new Page<>(1, 10);
        QueryWrapper<TaUv> taUvQueryWrapper = new QueryWrapper<>();
        taUvQueryWrapper.eq("be_uv", build.getBuildingId());
        taUvQueryWrapper.eq("tagert_type", CommConstant.FAVOR_PROJECT);
        taUvQueryWrapper.orderByDesc("create_date");
        IPage<TaUv> taUvList = taUvMapper.selectPage(page, taUvQueryWrapper);
        build.setUvList(taUvList);


        IPage<TaShare> pg = new Page<>(1, 10);
        QueryWrapper<TaShare> taShareQueryWrapper = new QueryWrapper<>();
        taShareQueryWrapper.eq("be_share", build.getBuildingId());
        taShareQueryWrapper.eq("tagert_type", CommConstant.FAVOR_PROJECT);
        taShareQueryWrapper.orderByDesc("create_date");
        IPage<TaShare> taShareList = taShareMapper.selectPage(pg, taShareQueryWrapper);
        build.setShareList(taShareList);

        build.setConsultants(taPersonMapper.selectBuildingConsultants(build.getBuildingId(), CommConstant.PERSON_REALTY_CONSULTANT, CommConstant.STATUS_NORMAL, build.getOrgId()));
    }

    @Override
    public ResponseBean getWxMainBuildingList(String cityId, Integer orgId) {
        List<TaBuilding> buildingList = taBuildingMapper.selectMainBuildings(cityId, orgId);
        if (null == buildingList) {
            return ResponseBean.success(new ArrayList<>());
        }

        for (TaBuilding building : buildingList) {
            String buildingId = building.getBuildingId();

            // 列表封面
            if (!StringUtils.isEmpty(building.getListPoster())) {
                List<TaBuildingImg> listImage = new ArrayList<>();
                TaBuildingImg img = new TaBuildingImg();
                img.setImgType(CommConstant.BUILDING_IMG_LIST);
                img.setBuildingId(buildingId);
                img.setUrl(building.getListPoster());
                listImage.add(img);
                building.setBuildingListImg(listImage);
            }

            // tags
            if (!StringUtils.isEmpty(building.getTags())) {
                List<TaBuildingTag> tags = new ArrayList<>();
                String[] tagsArray = building.getTags().split(",");
                for (String tagName : tagsArray) {
                    TaBuildingTag tag = new TaBuildingTag();
                    tag.setBuildingId(buildingId);
                    tag.setTagName(tagName);
                    tags.add(tag);
                }
                building.setBuildingTag(tags);
            }

            // Uv
            IPage<TaUv> pageUv = new Page<>(1, 10);
            QueryWrapper<TaUv> query3 = new QueryWrapper<>();
            query3.eq("be_uv", buildingId);
            query3.eq("tagert_type", CommConstant.FAVOR_PROJECT);
            query3.orderByDesc("create_date");
            IPage<TaUv> uvs = taUvMapper.selectPage(pageUv, query3);
            building.setUvList(uvs);

            // share num
            IPage<TaShare> pageSN = new Page<>(1, 10);
            pageSN.setTotal(null == building.getShareNum() ? 0l : building.getShareNum());
            building.setShareList(pageSN);
        }

        IPage<TaBuilding> page = new Page<>(1, 10);
        page.setTotal(buildingList.size());
        page.setRecords(buildingList);
        return ResponseBean.success(page);
    }

    @Override
    public ResponseBean getWxBuildingById(String buildingId) {
        // 楼盘信息
        QueryWrapper<TaBuilding> buildingQueryWrapper = new QueryWrapper<>();
        buildingQueryWrapper.eq("building_id", buildingId);
        TaBuilding building = taBuildingMapper.selectOne(buildingQueryWrapper);
        if (null == building) {
            return ResponseBean.error("项目不存在", ResponseBean.ERROR_ILLEGAL_PARAMS);
        }

        // 楼盘Banner
        QueryWrapper<TaBuildingImg> buildingImgBannerQueryWrapper = new QueryWrapper<>();
        buildingImgBannerQueryWrapper.eq("building_id", building.getBuildingId());
        buildingImgBannerQueryWrapper.eq("img_type", CommConstant.BUILDING_IMG_BANNER);
        buildingImgBannerQueryWrapper.orderBy(true, true, "order_no");
        List<TaBuildingImg> buildingBannerImg = taBuildingImgMapper.selectList(buildingImgBannerQueryWrapper);

        building.setBuildingImg(buildingBannerImg);

        // 楼盘户型
        QueryWrapper<TaBuildingApartment> buildingApartmentQueryWrapper = new QueryWrapper<>();
        buildingApartmentQueryWrapper.eq("building_id", building.getBuildingId());
        buildingApartmentQueryWrapper.orderByDesc("order_no");
        buildingApartmentQueryWrapper.orderByDesc("create_date");
        List<TaBuildingApartment> buildingApartmentList = taBuildingApartmentMapper.selectList(buildingApartmentQueryWrapper);

        // 楼盘户型图
        buildingApartmentList.forEach(e -> {
            QueryWrapper<TaBuildingImg> buildingImgQueryWrapper = new QueryWrapper<>();
            buildingImgQueryWrapper.eq("building_id", building.getBuildingId());
            List<TaBuildingImg> buildingImgList = taBuildingImgMapper.selectList(buildingImgQueryWrapper);
            e.setBuildingImgList(buildingImgList);
        });

        Map<String, Object> buildingMap = new HashMap<>();
        buildingMap.put("info", building);
        buildingMap.put("buildingApartment", buildingApartmentList);

        return ResponseBean.success(buildingMap);
    }

    @Override
    public ResponseBean buildingApartmentBuildingId(String id, String apartmentType) {
        QueryWrapper<TaBuildingApartment> buildingApartmentQueryWrapper = new QueryWrapper<>();
        buildingApartmentQueryWrapper.eq("building_id", id);
        buildingApartmentQueryWrapper.eq("status", 1);
        buildingApartmentQueryWrapper.eq(org.apache.commons.lang3.StringUtils.isNotBlank(apartmentType), "apartment_type", apartmentType);
        buildingApartmentQueryWrapper.orderByDesc("order_no");
        buildingApartmentQueryWrapper.orderByDesc("create_date");
        List<TaBuildingApartment> buildingApartment = taBuildingApartmentMapper.selectList(buildingApartmentQueryWrapper);
        buildingApartment.forEach(e -> {
            QueryWrapper<TaApartmentImg> ApartmentImgQueryWrapper = new QueryWrapper<>();
            ApartmentImgQueryWrapper.eq("apartment_id", e.getApartmentId());
            List<TaApartmentImg> buildingImg = taApartmentImgMapper.selectList(ApartmentImgQueryWrapper);

            List<TaBuildingImg> buildingImag = buildingImg.stream().map(img -> {
                QueryWrapper<TaBuildingImg> buildingImgQueryWrapper = new QueryWrapper<>();
                buildingImgQueryWrapper.eq("img_id", img.getImgId());
                buildingImgQueryWrapper.eq("img_type", CommConstant.BUILDING_IMG_APARMENT);
                return taBuildingImgMapper.selectOne(buildingImgQueryWrapper);
            }).sorted(Comparator.comparing(TaBuildingImg::getOrderNo)).collect(Collectors.toList());

            e.setBuildingImgList(buildingImag);

        });

        return ResponseBean.success(buildingApartment);
    }

    @Override
    public ResponseBean apartmentDel(String id) {
        QueryWrapper<TaBuildingApartment> buildingApartmentQueryWrapper = new QueryWrapper<>();
        buildingApartmentQueryWrapper.eq("apartment_id", id);
        TaBuildingApartment buildingApartment = taBuildingApartmentMapper.selectOne(buildingApartmentQueryWrapper);

//        TaBuilding  building= new TaBuilding();
        QueryWrapper<TaBuilding> buildingtWrapper = new QueryWrapper<>();
        buildingtWrapper.lambda().eq(TaBuilding::getBuildingId, buildingApartment.getBuildingId());
//        TaBuilding bui= taBuildingMapper.selectOne(buildingtWrapper);
//        if (bui.getStatus().equals(1)){
//            return ResponseBean.error("楼盘已发布不可以删除", ResponseBean.ERROR_UNAVAILABLE);
//        }

        buildingApartment.setStatus(-1);
        taBuildingApartmentMapper.update(buildingApartment, buildingApartmentQueryWrapper);

        return ResponseBean.success("");
    }

    @Override
    public ResponseBean buildingAll(Integer orgId) {
        List<TaBuilding> taBuilding = taBuildingMapper.buildingAll(orgId);
        return ResponseBean.success(taBuilding);
    }

    @Override
    public Integer getCityById(String buildingId) {
        if (StringUtils.isEmpty(buildingId)) return null;

        TaBuilding taBuilding = taBuildingMapper.selectById(buildingId);
        if (null == taBuilding) return null;

        return taBuilding.getCityId();
    }

    @Override
    public ResponseBean getBuildingListById(Integer orgId, Integer cityId) {
        List<TaBuilding> buildings = taBuildingMapper.getBuildingListById(orgId, cityId);
        return ResponseBean.success(buildings);
    }

    @Override
    public int countNumByHeavy(Integer heavy, String dynamicId) {
        return taBuildingMapper.countNumByHeavy(heavy, dynamicId);
    }

    /**
     * 推荐到首页楼盘不能超过10个
     *
     * @param taBuilding
     * @return
     */
    public boolean publishCountIsMainBuilding(TaBuilding taBuilding, Integer orgId, Integer status, String operte) {
        QueryWrapper<TaBuilding> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("building_id", taBuilding.getBuildingId());
        queryWrapper.eq("org_id", orgId);
        TaBuilding info = taBuildingMapper.selectOne(queryWrapper);
        if (taBuilding.getIsMain() != 1) {
            return true;
        }
//        if (operte.equals("update") && (info.getStatus() == 2)){
//            return true;
//        }
        if (operte.equals("updateStatus") && status == 2) {
            return true;
        }
        QueryWrapper<TaBuilding> taBuildingQueryWrapper = new QueryWrapper<>();
        taBuildingQueryWrapper.eq("city_id", taBuilding.getCityId());
        taBuildingQueryWrapper.eq("is_main", 1);
        taBuildingQueryWrapper.eq("org_id", orgId);
        taBuildingQueryWrapper.ne("status", "-1");
        taBuildingQueryWrapper.ne("status", "2");
        if (taBuilding.getBuildingId() != null) {
            taBuildingQueryWrapper.ne("building_id", taBuilding.getBuildingId());
        }
        List<TaBuilding> taBuildings = taBuildingMapper.selectList(taBuildingQueryWrapper);
        if (taBuildings != null && taBuildings.size() >= 10) {
            return false;
        }
        return true;
    }


    private List<TaBuildingImg> insertImgBatch(List<TaBuildingImg> imgs, String buildingId) {
        return imgs.stream().map(img -> {
            TaBuildingImg Images = new TaBuildingImg();
            Images.setBuildingId(buildingId);
            Images.setImgType(img.getImgType());
            Images.setUrl(img.getUrl());
            Images.setOrderNo(Integer.valueOf(img.getOrderNo()));
            Images.setStatus(1);
            Images.setCreateDate(LocalDateTime.now());
            taBuildingImgMapper.insert(Images);

            return Images;
        }).collect(Collectors.toList());
    }

    private List<TaBuildingTag> insertTagBatch(List<TaBuildingTag> tags, String buildingId) {
        return tags.stream().map(tag -> {
            TaBuildingTag btag = new TaBuildingTag();
            btag.setBuildingId(buildingId);
            btag.setTagName(tag.getTagName());
            taBuildingTagMapper.insert(btag);
            return btag;
        }).collect(Collectors.toList());
    }

    int insertApartmentImgBatch(List<TaBuildingImg> imgs, String buildingId, String apartmentId) {
        int rows = 0;
        for (TaBuildingImg img : imgs) {
            TaBuildingImg Images = new TaBuildingImg();
            Images.setBuildingId(buildingId);
            Images.setImgType(img.getImgType());
            Images.setUrl(img.getUrl());
            Images.setOrderNo(Integer.valueOf(img.getOrderNo()));
            Images.setStatus(1);
            Images.setCreateDate(LocalDateTime.now());

            if (taBuildingImgMapper.insert(Images) < 1) {
                continue;
            }
            ;

            TaApartmentImg apartmentImg = new TaApartmentImg();
            apartmentImg.setApartmentId(apartmentId);
            apartmentImg.setImgId(Images.getImgId());
            apartmentImg.setStatus(1);
            rows += taApartmentImgMapper.insert(apartmentImg);
        }

        return rows;
    }
}
