package com.tourism.webadmin.app.website.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.github.pagehelper.page.PageMethod;
import com.tourism.common.additional.utils.StringUtils;
import com.tourism.common.additional.utils.UrlConvertUtils;
import com.tourism.common.core.base.vo.BaseVo;
import com.tourism.common.core.object.*;
import com.tourism.common.core.util.MyCommonUtil;
import com.tourism.common.core.util.MyModelUtil;
import com.tourism.common.core.util.MyPageUtil;
import com.tourism.common.huaweicloud.obs.util.MergeAvatarsFlexUtils;
import com.tourism.webadmin.app.website.controller.TourGroupController;
import com.tourism.webadmin.app.website.controller.TourWebFansController;
import com.tourism.webadmin.app.website.dto.TourWebFansDto;
import com.tourism.webadmin.app.website.dto.TourismBannerDto;
import com.tourism.webadmin.app.website.dto.TourismProjectTravelNotesToWebDto;
import com.tourism.webadmin.app.website.dto.TourismTravelNotesWriteDto;
import com.tourism.webadmin.app.website.service.BasicToWebService;
import com.tourism.webadmin.app.website.service.TourGroupService;
import com.tourism.webadmin.back.model.*;
import com.tourism.webadmin.back.model.constant.*;
import com.tourism.webadmin.back.service.*;
import com.tourism.webadmin.back.service.impl.TourUserServiceImpl;
import com.tourism.webadmin.back.vo.*;
import com.tourism.common.additional.config.ApplicationConfig;
import com.tourism.webadmin.enums.MyAttentionStatus;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 门户网站首页Service
 *
 * @author tourism
 */
@Slf4j
@Service("BasicToWebService")
public class BasicToWebServiceImpl implements BasicToWebService
{

    @Autowired
    private BannerInfoService bannerInfoService;
    @Autowired
    private DirectoryInfoService directoryInfoService;
    @Autowired
    private ApplicationConfig applicationConfig;
    @Autowired
    private TourTourismProjectTravelNotesService tourTourismProjectTravelNotesService;
    @Autowired
    private TourUserLikeTravelNotesService tourUserLikeTravelNotesService;
    @Autowired
    private TourismProjectTravelNotesWriteService tourismProjectTravelNotesWriteService;
    @Autowired
    private TourBusinessBannerService tourBusinessBannerService;
    @Autowired
    private TourTravelNotesImgService tourTravelNotesImgService;
    @Autowired
    private TourImMemberService tourImMemberService;
    @Autowired
    private TourUserServiceImpl tourUserService;
    @Autowired
    private MergeAvatarsFlexUtils mergeAvatarsFlexUtils;
    @Autowired
    private TourGroupService tourGroupService;
    @Autowired
    private TourImGroupTypeService tourImGroupTypeService;
    @Autowired
    private TourWebFansController tourWebFansController;
    @Autowired
    private TourGroupController tourGroupController;
    @Autowired
    private TourismTravelNotesContentWriteService tourismTravelNotesContentWriteService;



    @Override
    public MyPageData<BannerInfoVo> getBannerInfoList(TourismBannerDto tourismBannerDto) {

        BannerInfo bannerInfoFilter = new BannerInfo();
        bannerInfoFilter.setBelongTab(tourismBannerDto.getBelongTab());
        //默认查PC的轮播图
        if(tourismBannerDto.getType() == null){
            bannerInfoFilter.setType(0);
        }else {
            bannerInfoFilter.setType(tourismBannerDto.getType());
        }
        //首页展示的话，只能展示启用的banner图
        bannerInfoFilter.setEnable(1);
        MyOrderParam.OrderInfo orderInfo = new MyOrderParam.OrderInfo();
        orderInfo.setFieldName("mainBanner");
        orderInfo.setAsc(false);
        MyOrderParam myOrderParam  = new MyOrderParam();
        myOrderParam.add(orderInfo);
        myOrderParam.add(new MyOrderParam.OrderInfo("updateTime",false,null));
        String orderBy = MyOrderParam.buildOrderBy(myOrderParam, BannerInfo.class);
        List<BannerInfo> bannerInfoList = bannerInfoService.getBannerInfoListWithRelation(bannerInfoFilter, orderBy);
        MyPageData<BannerInfoVo> bannerInfoVoMyPageData = MyPageUtil.makeResponseData(bannerInfoList, BannerInfoVo.class);

        List<BannerInfoVo> dataList = bannerInfoVoMyPageData.getDataList();
            //先把imgUrl由jaon转换为List<FileUrlObject>
        dataList.stream().forEach(item ->{
            item.setImgUrlsAfterConvert(UrlConvertUtils.urlConvert(applicationConfig.getHostIpPort(), item.getImgUrl()));
        });

        return bannerInfoVoMyPageData;
    }

    @Override
    public MyPageData<DirectoryInfoVo> getDirectoryInfoList(Long parentId, Integer isHotspot, Integer isAll) {

        DirectoryInfo directoryInfoFilter = new DirectoryInfo();
        //当directoryId为1000时,则表明查询三级菜单
        if(parentId != null){
            directoryInfoFilter.setParentId(parentId);
        }
        if(isAll!= null && isAll == 1){
            directoryInfoFilter.setDirectoryId(1000L);
            //菜单类型：1：旅游，2：劳务
            directoryInfoFilter.setDirectoryType(1);
        }
        if(isHotspot != null){
            directoryInfoFilter.setIsHotspot(isHotspot);
        }
        MyOrderParam myOrderParam = new MyOrderParam();
        MyOrderParam.OrderInfo orderInfo = new MyOrderParam.OrderInfo();
        //先根据是否热点排序，再根据展示顺序排序
        orderInfo.setFieldName("isHotspot");
        orderInfo.setAsc(false);
        myOrderParam.add(orderInfo);
        orderInfo.setFieldName("showOrder");
        orderInfo.setAsc(true);
        myOrderParam.add(orderInfo);
        myOrderParam.add(new MyOrderParam.OrderInfo("updateTime",false,null));
        String orderBy = MyOrderParam.buildOrderBy(myOrderParam, DirectoryInfo.class);
        //看到的项目为启用的项目
        directoryInfoFilter.setEnable(1);
        List<DirectoryInfo> directoryInfoList =
                directoryInfoService.getDirectoryInfoListWithRelation(directoryInfoFilter, orderBy);
//        List<DirectoryInfo> directoryInfoList =
//                directoryInfoService.getDirectoryInfoListWithRelation(directoryInfoFilter, orderBy);

        MyPageData<DirectoryInfoVo> directoryInfoVoMyPageData = MyPageUtil.makeResponseData(directoryInfoList, DirectoryInfoVo.class);

        List<DirectoryInfoVo> dataList = directoryInfoVoMyPageData.getDataList();
        //先把imgUrl由jaon转换为List<FileUrlObject>
        dataList.stream().forEach(item ->{
            item.setHotPictureUrlsAfterConvert(UrlConvertUtils.urlConvert(applicationConfig.getHostIpPort(), item.getHotPictureUrl()));
        });
        return directoryInfoVoMyPageData;
    }

    @Override
    public MyPageData<TourismProjectTravelNotesWriteVo> getTourTourismProjectTravelNotesList(TourismTravelNotesWriteDto tourismTravelNotesWriteDto){

        TourismProjectTravelNotesWrite tourismProjectTravelNotesWriteFilter = new TourismProjectTravelNotesWrite();
        tourismProjectTravelNotesWriteFilter.setUnmountState(UnmountState.LISTING);
        tourismProjectTravelNotesWriteFilter.setIsHotspot(Hotspot.HOTSPOT_YES);
        tourismProjectTravelNotesWriteFilter.setState(AuditState.SUCCEEDAUDIT);
        tourismProjectTravelNotesWriteFilter.setVisibleRange(VisibleRange.ALL);
        tourismProjectTravelNotesWriteFilter.setProjectTitle(tourismTravelNotesWriteDto.getProjectTitle());
//        TourTourismProjectTravelNotes tourTourismProjectTravelNotesFilter = new TourTourismProjectTravelNotes();
//        tourTourismProjectTravelNotesFilter.setEnable(1);
//        tourTourismProjectTravelNotesFilter.setIsHotspot(1);
        if(tourismTravelNotesWriteDto.getPageNum() != null && tourismTravelNotesWriteDto.getPageSize() != null) {
            PageMethod.startPage(tourismTravelNotesWriteDto.getPageNum(), tourismTravelNotesWriteDto.getPageSize(), true);
        }
        MyOrderParam myOrderParam = new MyOrderParam();
        myOrderParam.add(new MyOrderParam.OrderInfo("hotValue",false,null));
        myOrderParam.add(new MyOrderParam.OrderInfo("updateTime",false,null));
        String orderBy = MyOrderParam.buildOrderBy(myOrderParam, TourismProjectTravelNotesWrite.class);
        List<TourismProjectTravelNotesWrite> writeList = tourismProjectTravelNotesWriteService.getTourismProjectTravelNotesWriteListWithRelation(tourismProjectTravelNotesWriteFilter, orderBy);
//        List<TourTourismProjectTravelNotes> tourTourismProjectTravelNotesList = tourTourismProjectTravelNotesService.getTourTourismProjectTravelNotesList(tourismProjectTravelNotesWriteFilter, orderBy);
        MyPageData<TourismProjectTravelNotesWriteVo> pageData = MyPageUtil.makeResponseData(writeList, TourismProjectTravelNotesWriteVo.class);
        List<TourismProjectTravelNotesWriteVo> dataList = pageData.getDataList();
        dataList.stream().forEach(item->{
            item.setHomeHotPicturesAfterConvert(UrlConvertUtils.urlConvert(applicationConfig.getHostIpPort(), item.getTourismUrl()));
        });

        return pageData;
    }

    @Override
    public MyPageData<TourismProjectTravelNotesWriteVo> getTravelNotesPageList(TourismTravelNotesWriteDto dto){
        //当belongTab为1的时候，则表明查询全部的游记
        MyOrderParam myOrderParam = new MyOrderParam();
        myOrderParam.add(new MyOrderParam.OrderInfo("hotValue",false,null));
        myOrderParam.add(new MyOrderParam.OrderInfo("updateTime",false,null));
        String orderBy = MyOrderParam.buildOrderBy(myOrderParam, TourismProjectTravelNotesWrite.class);

        TourismProjectTravelNotesWrite tourismProjectTravelNotesWriteFilter = new TourismProjectTravelNotesWrite();
        tourismProjectTravelNotesWriteFilter.setVisibleRange(VisibleRange.ALL);
        tourismProjectTravelNotesWriteFilter.setState(AuditState.SUCCEEDAUDIT);
        tourismProjectTravelNotesWriteFilter.setProjectTitle(dto.getProjectTitle());
//        TourTourismProjectTravelNotes tourTourismProjectTravelNotes = new TourTourismProjectTravelNotes();

        if(dto.getIsFollow()!=null&&dto.getIsFollow().equals("1")){
            //查询关注用户ids
            ResponseResult<MyPageData<TourFansVo>> pageList = tourWebFansController.getMyConCern(new TourWebFansDto());
            List<TourFansVo> dataList = pageList.getData().getDataList();
            if(ObjectUtil.isEmpty(dataList)){
                return  MyPageUtil.makeResponseData(new ArrayList<>(), 0L);
            }
            Set<String> collect = dataList.stream().map(TourFansVo::getAttentionId).collect(Collectors.toSet());
            String userId = TokenData.takeFromRequest().getUserId().toString();
            //排除自己
            collect.remove(userId);
            tourismProjectTravelNotesWriteFilter.setCreatUserIdFilter(collect);
        }
        if(dto.getTravelWriteType() != null){
            if(dto.getTravelWriteType().equals(1)){
               //是否原创(0:非原创;1:原创)。
                tourismProjectTravelNotesWriteFilter.setIsOriginal(1);
            }else if(dto.getTravelWriteType().equals(2)){
                tourismProjectTravelNotesWriteFilter.setIsOriginal(0);
            }
        }

        if (MyCommonUtil.isNotBlankOrNull(dto.getSearchString())){
            tourismProjectTravelNotesWriteFilter.setSearchString(dto.getSearchString());
        }
        if(StringUtils.isEmpty(dto.getAreaId()) && StringUtils.isEmpty(dto.getCountryId())){
            //判断是否为全部的地区
            tourismProjectTravelNotesWriteFilter.setUnmountState(1);
            tourismProjectTravelNotesWriteFilter.setEndPlace(null);
        }else if(StringUtils.isNotEmpty(dto.getAreaId()) && StringUtils.isEmpty(dto.getCountryId())){
            //判断是否为该地区的所有国家
            DirectoryInfo directoryInfo = new DirectoryInfo();
            directoryInfo.setParentId(Long.parseLong(dto.getAreaId()));
            directoryInfo.setEnable(1);
            List<DirectoryInfo> directoryInfoList =
                    directoryInfoService.getDirectoryInfoList(directoryInfo, "");
            List<Long> directoryIdList =
                    directoryInfoList.stream().map(DirectoryInfo::getId).collect(Collectors.toList());
            tourismProjectTravelNotesWriteFilter.setEndPlace(null);
            tourismProjectTravelNotesWriteFilter.setDirectoryInfoIds(directoryIdList);
        }else {
            //如果查询的是某个国家的游记的话
            if(StringUtils.isNotEmpty(dto.getCountryId())) {
                tourismProjectTravelNotesWriteFilter.setEndPlace(Long.parseLong(dto.getCountryId()));
            }
        }

        if(dto.getPageNum() != null && dto.getPageSize() != null) {
            PageMethod.startPage(dto.getPageNum(), dto.getPageSize(), true);
        }
        if(ObjectUtil.isEmpty(dto.getIsHotspot())){
            tourismProjectTravelNotesWriteFilter.setIsHotspot(dto.getIsHotspot());
        }
//        List<TourTourismProjectTravelNotes> tourTourismProjectTravelNotesList =
//                tourTourismProjectTravelNotesService.getTourTourismProjectTravelNotesList(tourismProjectTravelNotesWriteFilter, orderBy);
        List<TourismProjectTravelNotesWrite> writeList =
                tourismProjectTravelNotesWriteService.getTourismProjectTravelNotesWriteList(tourismProjectTravelNotesWriteFilter, orderBy);
        MyPageData<TourismProjectTravelNotesWriteVo> pageData =
                MyPageUtil.makeResponseData(writeList, TourismProjectTravelNotesWriteVo.class);

        List<TourismProjectTravelNotesWriteVo> dataList = pageData.getDataList();

        dataList.stream().forEach(item->{
            item.setTourismUrlsAfterConvert(UrlConvertUtils.urlConvert(applicationConfig.getHostIpPort(), item.getTourismUrl()));
        });

        //填充创建人和头像
        Set<Long> collect = dataList.stream().map(BaseVo::getCreateUserId).collect(Collectors.toSet());

        List<TourUser> inList = tourUserService.getInList(collect);
        HashMap<String, TourUser> userHashMap = new HashMap<>();
        for (TourUser tourUser : inList) {
            userHashMap.put(tourUser.getUserId().toString(),tourUser);
        }
        for (TourismProjectTravelNotesWriteVo vo :pageData.getDataList()) {
            TourUser tourUser = userHashMap.get(vo.getCreateUserId().toString());
            if(tourUser!=null){
                vo.setCreateImage(tourUser.getHeadImageUrl());
                vo.setCreateName(tourUser.getShowName());
            }
        }
        return pageData;
    }

    @Override
    public TourismProjectTravelNotesWriteVo travelNotesDetail(String id){
        TourismProjectTravelNotesWrite writeDto = tourismProjectTravelNotesWriteService.getByIdWithRelation(Long.parseLong(id), MyRelationParam.full());
        if(ObjectUtil.isEmpty(writeDto)){
            return null;
        }
        if(writeDto.getTourImGroupId()!=null){
            TourImGroup byId = tourGroupService.getById(writeDto.getTourImGroupId());
            writeDto.setTourImGroup(byId);
        }

        if(writeDto.getPageViewCount() != null) {
            writeDto.setPageViewCount(writeDto.getPageViewCount() + 1);
        }else {
            writeDto.setPageViewCount(1);
        }
        //每有一人浏览，则增加50热度值
        if(writeDto.getHotValue() != null) {
            writeDto.setHotValue(writeDto.getHotValue() + 50);
        }else {
            writeDto.setHotValue(50);
        }
        tourismProjectTravelNotesWriteService.updateById(writeDto);

        TourismProjectTravelNotesWriteVo writeVo =
                MyModelUtil.copyTo(writeDto, TourismProjectTravelNotesWriteVo.class);
        writeVo.setCreateUser(writeDto.getCreateUserId().toString());
        writeVo.setTourismUrlsAfterConvert(UrlConvertUtils.urlConvert(applicationConfig.getHostIpPort(), writeVo.getTourismUrl()));
        writeVo.setHomeHotPicturesAfterConvert(UrlConvertUtils.urlConvert(applicationConfig.getHostIpPort(), writeVo.getTourismUrl()));
        writeVo.setTravelNotesBannerAfterConvert(UrlConvertUtils.urlConvert(applicationConfig.getHostIpPort(), writeVo.getTravelNotesBanner()));

        DirectoryInfo directoryInfo = directoryInfoService.getById(writeVo.getEndPlace());
        if(directoryInfo.getParentId() != null) {
            DirectoryInfo directoryInfo1 = directoryInfoService.getById(directoryInfo.getParentId());
            writeVo.setEndArea(directoryInfo1.getMenuName());
        }

        //查询关联的照片图集
        TourTravelNotesImg tourTravelNotesImg = new TourTravelNotesImg();
        tourTravelNotesImg.setTravelNotesId(Long.parseLong(writeVo.getId()));
        List<TourTravelNotesImg> tourTravelNotesImgList = tourTravelNotesImgService.getTourTravelNotesImgList(tourTravelNotesImg, "");
        List<String> imgUrls = tourTravelNotesImgList.stream().map(TourTravelNotesImg::getImgUrl).collect(Collectors.toList());
        writeVo.setImgUrls(imgUrls);

        //设置群聊信息
        //如果群聊没有设置群聊头像的话，则进行拼接群聊头像
        if(!ObjectUtil.isEmpty(writeDto.getTourImGroup())&&ObjectUtil.isEmpty(writeDto.getTourImGroup().getGroupAvatar()) && writeVo.getTourImGroupId() != null) {
            TourImMember tourImMember = new TourImMember();
            tourImMember.setGroupId(Long.parseLong(writeVo.getTourImGroupId()));
            List<TourImMember> tourImMemberList = tourImMemberService.getTourImMemberList(tourImMember, "");
            // 如果群聊为空的话，则该群聊是被解散了
            if(!CollectionUtils.isEmpty(tourImMemberList)){
                List<TourImMember> tourImMembers = new ArrayList<>();
                if(tourImMemberList.size() > 9) {
                    tourImMembers = tourImMemberList.subList(0, 9);
                }else {
                    tourImMembers = tourImMemberList.subList(0,tourImMemberList.size());
                }
                List<Long> userIdList = tourImMembers.stream().map(TourImMember::getUserId).collect(Collectors.toList());

                List<TourUser> userList = tourUserService.getInList("userId", new HashSet<>(userIdList));
                List<String> userHeadImgUrlList = userList.stream().map(TourUser::getHeadImageUrl).collect(Collectors.toList());
                //设置群聊头像
                writeVo.getTourImGroup().setGroupAvatar(mergeAvatarsFlexUtils.mergeAndUploadAvatars(userHeadImgUrlList));
                //设置群聊人数
                writeVo.setTourImGroupCount(tourImMemberList.size());
                //群主
                TourUser byId1 = tourUserService.getById( writeVo.getTourImGroup().getLeaderId());
                //类型
                if( writeVo.getTourImGroup().getBelongTypeId()!=null){
                    TourImGroupType type = tourImGroupTypeService.getById( writeVo.getTourImGroup().getBelongTypeId());
                    HashMap<String, Object> longObjectHashMap = new HashMap<>();
                    longObjectHashMap.put(type.getId().toString(),type);
                    writeVo.getTourImGroup().setBelongTypeIdDictMap(longObjectHashMap);
                }
                writeVo.setGroupOwnerName(byId1.getShowName());
                writeVo.setGroupOwnerImage(byId1.getHeadImageUrl());
                writeVo.setGroupOwnerId(byId1.getUserId().toString());
            }
        }
        if (writeVo.getCreateUserId()!=null) {
            TourUser creatUser = tourUserService.getById(writeDto.getCreateUserId());
            if(creatUser!=null){
                writeVo.setCreateImage(creatUser.getHeadImageUrl());
                writeVo.setCreateName(creatUser.getShowName());
            }
            if(TokenData.takeFromRequest()!=null){
                Long l = tourGroupController.attentionStatus(writeVo.getCreateUserId());
                writeVo.setUserState(l.toString());
                Long userId = TokenData.takeFromRequest().getUserId();

                //是否收藏
                List<TourUserLikeTravelNotes> list = tourUserLikeTravelNotesService.lambdaQuery()
                        .eq(TourUserLikeTravelNotes::getTravelNotesId, writeVo.getId())
                        .eq(TourUserLikeTravelNotes::getUserId, userId).list();
                if (ObjectUtil.isEmpty(list)) {
                    writeVo.setIsCollect(0);
                } else {
                    writeVo.setIsCollect(1);
                }
            }else {
                writeVo.setIsCollect(0);
                writeVo.setIsLike(0);
                writeVo.setUserState(MyAttentionStatus.UN_FOCUS.toString());
            }
            //收藏数量
            TourUserLikeTravelNotes tourUserLikeTravelNotes = new TourUserLikeTravelNotes();
            tourUserLikeTravelNotes.setTravelNotesId(Long.valueOf(writeVo.getId()));
            long countByFilter = tourUserLikeTravelNotesService.getCountByFilter(tourUserLikeTravelNotes);
            writeVo.setCollectCount(countByFilter);
        }
        if(ObjectUtil.isEmpty(writeVo.getImgUrls())){
            //图片
            Set<String> image = writeVo.getTravelNotesContent().stream().filter(item ->
                    item.getType().equals("image")
            ).map(TourismTravelNotesContentWriteVo::getContent).collect(Collectors.toSet());
            if(image.isEmpty()){
                image.addAll(writeVo.getTravelNotesBannerAfterConvert());
            }
            writeVo.setImgUrls(new ArrayList<String>(image));
            //图片
            List<TourismTravelNotesContentWriteVo> collect = writeVo.getTravelNotesContent().stream().filter(item ->
                    item.getType().equals("sectionContent")|| item.getType().equals("sectionTitle")
            ).collect(Collectors.toList());
            Map<String, Object> map=new HashMap<>();
            StringBuilder content = new StringBuilder();
            for (TourismTravelNotesContentWriteVo travelNotesContentWriteVo : collect) {
                String s="";
                if(travelNotesContentWriteVo.getType().equals("sectionContent")){
                  s="<p>"+travelNotesContentWriteVo.getContent()+"</p>";

                }else {
                    s="<div class=\"py-15 text-5xl text-black-3\">"+travelNotesContentWriteVo.getContent()+"</div>";
                }
                content.append(s);
            }
            map.put("content",content.toString());
            if(!collect.isEmpty()){
                map.put("associationId",collect.get(0).getAssociationId());
            }
            writeVo.setTourTourismProjectTravelNotesWriteContent(map);
        }
        return writeVo;
    }

    @Override
    @Transactional
    public void userLikeTravelNotesUpdate(Long travelNotesId,Integer type){

//        TourUserLikeTravelNotes tourUserLikeTravelNotes =
//                new TourUserLikeTravelNotes();
//        tourUserLikeTravelNotes.setTravelNotesId(travelNotesId);
//        tourUserLikeTravelNotes.setUserId(TokenData.takeFromRequest().getUserId());
//        TourTourismProjectTravelNotes tourTourismProjectTravelNotes = tourTourismProjectTravelNotesService.getById(travelNotesId);
//        if(tourTourismProjectTravelNotes.getLikeCount() != null) {
//            if(type == 1) {
//                tourTourismProjectTravelNotes.setLikeCount(tourTourismProjectTravelNotes.getLikeCount() + 1);
//                if(tourTourismProjectTravelNotes.getHotValue() != null) {
//                    tourTourismProjectTravelNotes.setHotValue(tourTourismProjectTravelNotes.getHotValue() + 100);
//                }else {
//                    tourTourismProjectTravelNotes.setHotValue(100);
//                }
//            }else {
//                tourTourismProjectTravelNotes.setLikeCount(tourTourismProjectTravelNotes.getLikeCount() - 1);
//            }
//        }else {
//            tourTourismProjectTravelNotes.setLikeCount(1);
//        }
//        if(type == 0){
//            tourUserLikeTravelNotesService.removeBy(tourUserLikeTravelNotes);
//        }else {
//            tourUserLikeTravelNotesService.saveNew(tourUserLikeTravelNotes);
//        }
//        TourTourismProjectTravelNotes tourTourismProjectTravelNotes = tourTourismProjectTravelNotesService.getById(travelNotesId);
//        if(tourTourismProjectTravelNotes != null) {
//            if (tourTourismProjectTravelNotes.getLikeCount() == null) {
//                tourTourismProjectTravelNotes.setLikeCount(1);
//            } else {
//                tourTourismProjectTravelNotes.setLikeCount(tourTourismProjectTravelNotes.getLikeCount() + 1);
//            }
//            tourTourismProjectTravelNotesService.updateById(tourTourismProjectTravelNotes);
//        }
        //type为0，则进行删除;type为1，则进行新增
        TourUserLikeTravelNotes tourUserLikeTravelNotes = new TourUserLikeTravelNotes();
        tourUserLikeTravelNotes.setTravelNotesId(travelNotesId);
        tourUserLikeTravelNotes.setUserId(TokenData.takeFromRequest().getUserId());
        if(type == 0){
            tourUserLikeTravelNotesService.removeBy(tourUserLikeTravelNotes);
        }else {
            boolean b = tourUserLikeTravelNotesService.existByFilter(tourUserLikeTravelNotes);
            if(!b){
                tourUserLikeTravelNotesService.saveNew(tourUserLikeTravelNotes);
            }

        }

    }

    @Override
    public Boolean isLikeTravelNotes(Long travelNotesId){
        TourUserLikeTravelNotes tourUserLikeTravelNotes = new TourUserLikeTravelNotes();
        tourUserLikeTravelNotes.setTravelNotesId(travelNotesId);
        tourUserLikeTravelNotes.setUserId(TokenData.takeFromRequest().getUserId());
        return tourUserLikeTravelNotesService.existByFilter(tourUserLikeTravelNotes);

    }

    @Override
    public void travelNotesViewCountAdd(Long travelNotesId){

        TourismProjectTravelNotesWrite tourismProjectTravelNotesWrite = tourismProjectTravelNotesWriteService.getById(travelNotesId);
        if(tourismProjectTravelNotesWrite.getPageViewCount() != null) {
            tourismProjectTravelNotesWrite.setPageViewCount(tourismProjectTravelNotesWrite.getPageViewCount() + 1);
        }else {
            tourismProjectTravelNotesWrite.setPageViewCount(1);
        }
        //每有一人浏览，则增加50热度值
        if(tourismProjectTravelNotesWrite.getHotValue() != null) {
            tourismProjectTravelNotesWrite.setHotValue(tourismProjectTravelNotesWrite.getHotValue() + 50);
        }else {
            tourismProjectTravelNotesWrite.setHotValue(50);
        }
        tourismProjectTravelNotesWriteService.updateById(tourismProjectTravelNotesWrite);
    }

    @Override
    public void generate(){
        //随机生成1k-2w的浏览量,浏览量除以2为（点赞数的上限)浏览量除以3为(点赞数的下限),热度值为浏览量的二倍以上-三倍以下随机数,这三个数值都为整数
        List<TourTourismProjectTravelNotes> tourTourismProjectTravelNotesList =
                tourTourismProjectTravelNotesService.getTourTourismProjectTravelNotesList(new TourTourismProjectTravelNotes(), "");

        tourTourismProjectTravelNotesList.stream().forEach(item->{

            Random random = new Random();
            // 生成1k-2w的浏览量
            int minViews = 1000;
            int maxViews = 20000;
            int views = random.nextInt(maxViews - minViews + 1) + minViews;

            // 计算点赞数的上限和下限
            int maxLikes = views / 3;
            int minLikes = views / 4;
            int likes = random.nextInt(maxLikes - minLikes + 1) + minLikes;

            // 生成热度值（）
            int heat = (views*50)+(likes*100);

            item.setHotValue(heat);
            item.setLikeCount(likes);
            item.setPageViewCount(views);

            tourTourismProjectTravelNotesService.updateById(item);
        });
    }

    @Override
    public List<TourBusinessBanner> getTourBusinessBannerList(Long businessType) {
        // 根据业务类型查询banner列表
        TourBusinessBanner tourBusinessBannerFilter = new TourBusinessBanner();
        tourBusinessBannerFilter.setBusinessType(businessType);
        MyOrderParam myOrderParam = new MyOrderParam();
        // 按照showOrder字段升序排序
        myOrderParam.add(new MyOrderParam.OrderInfo("showOrder", true, null));
        String orderBy = MyOrderParam.buildOrderBy(myOrderParam, TourBusinessBanner.class);
        List<TourBusinessBanner> tourBusinessBannerList =
                tourBusinessBannerService.getTourBusinessBannerListWithRelation(tourBusinessBannerFilter, orderBy);
        return tourBusinessBannerList;
    }
}

