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

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.object.MyOrderParam;
import com.tourism.common.core.object.MyPageData;
import com.tourism.common.core.object.MyRelationParam;
import com.tourism.common.core.object.TokenData;
import com.tourism.common.core.util.MyModelUtil;
import com.tourism.common.core.util.MyPageUtil;
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.back.model.*;
import com.tourism.webadmin.back.model.constant.AuditState;
import com.tourism.webadmin.back.model.constant.Hotspot;
import com.tourism.webadmin.back.model.constant.TravelWriteType;
import com.tourism.webadmin.back.model.constant.UnmountState;
import com.tourism.webadmin.back.service.*;
import com.tourism.webadmin.back.vo.*;
import com.tourism.common.additional.config.ApplicationConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Random;
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;

    @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);
//        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("isHotspot",false,null));
        myOrderParam.add(new MyOrderParam.OrderInfo("updateTime",false,null));
        String orderBy = MyOrderParam.buildOrderBy(myOrderParam, TourismProjectTravelNotesWrite.class);

        TourismProjectTravelNotesWrite tourismProjectTravelNotesWriteFilter = new TourismProjectTravelNotesWrite();
//        TourTourismProjectTravelNotes tourTourismProjectTravelNotes = new TourTourismProjectTravelNotes();

        if(dto.getTravelWriteType() != null){
            if(dto.getTravelWriteType().equals(TravelWriteType.ORIGINAL)){
               //是否原创(0:非原创;1:原创)。
                tourismProjectTravelNotesWriteFilter.setIsOriginal(1);
            }
        }
        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);
        }

//        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()));
        });

        return pageData;
    }

    @Override
    public TourismProjectTravelNotesWriteVo travelNotesDetail(String id){
        TourismProjectTravelNotesWrite writeDto = tourismProjectTravelNotesWriteService.getByIdWithRelation(Long.parseLong(id), MyRelationParam.full());
        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);

        if(writeVo != null) {
            writeVo.setTourismUrlsAfterConvert(UrlConvertUtils.urlConvert(applicationConfig.getHostIpPort(), writeVo.getTourismUrl()));
            writeVo.setHomeHotPicturesAfterConvert(UrlConvertUtils.urlConvert(applicationConfig.getHostIpPort(), writeVo.getTourismUrl()));
            writeVo.setTravelNotesBannerAfterConvert(UrlConvertUtils.urlConvert(applicationConfig.getHostIpPort(), writeVo.getTravelNotesBanner()));
        }
        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;
    }
}

