package com.tourism.webadmin.app.website.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import com.github.pagehelper.page.PageMethod;
import com.tourism.common.additional.config.ApplicationConfig;
import com.tourism.common.additional.utils.UrlConvertUtils;
import com.tourism.common.core.constant.ErrorCodeEnum;
import com.tourism.common.core.object.MyOrderParam;
import com.tourism.common.core.object.MyPageData;
import com.tourism.common.core.object.ResponseResult;
import com.tourism.common.core.object.TokenData;
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.core.validator.UpdateGroup;
import com.tourism.common.log.annotation.OperationLog;
import com.tourism.common.log.model.constant.SysOperationLogType;
import com.tourism.webadmin.app.website.dto.PageDto;
import com.tourism.webadmin.app.website.dto.TourismCollectDto;
import com.tourism.webadmin.app.website.dto.TourismTravelNotesWriteDto;
import com.tourism.webadmin.app.website.service.BasicToWebService;
import com.tourism.webadmin.app.website.vo.TourTravelNotesDirectoryCountryVo;
import com.tourism.webadmin.app.website.vo.TourTravelNotesDirectoryVo;
import com.tourism.webadmin.app.website.vo.TourismProjectTravelNotesWriteCovertVo;
import com.tourism.webadmin.back.model.*;
import com.tourism.webadmin.back.model.constant.UnmountState;
import com.tourism.webadmin.back.service.*;
import com.tourism.webadmin.back.vo.TourismProjectTravelNotesWriteVo;
import com.tourism.webadmin.back.vo.TourismProjectVo;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

@Tag(name = "门户网站旅游游记接口")
@Slf4j
@RestController
@Validated
@RequestMapping("/website/tourism/projectTravelNotes")
public class WebsiteTourismProjectTravelNotesController {

    @Autowired
    private BasicToWebService basicToWebServicel;
    @Autowired
    private DirectoryInfoService directoryInfoService;
    @Autowired
    private TourTravelNotesProjectRelationService tourTravelNotesProjectRelationService;
    @Autowired
    private TourismProjectService tourismProjectService;
    @Autowired
    private TourTourismProjectTravelNotesService tourTourismProjectTravelNotesService;
    @Autowired
    private ApplicationConfig applicationConfig;
    @Autowired
    private TourUserLikeTravelNotesService tourUserLikeTravelNotesService;
    @Autowired
    private TourismProjectTravelNotesWriteService tourismProjectTravelNotesWriteService;


    /**
     * 列出旅游游记列表。(首页)
     * @return 应答结果对象，包含查询结果集。
     */
    @OperationLog(type = SysOperationLogType.LIST)
    @GetMapping("/homeList")
    @SaIgnore
    public ResponseResult<MyPageData<TourismProjectTravelNotesWriteVo>> tourTourismTravelNotesList(TourismTravelNotesWriteDto tourismTravelNotesWriteDto) {
        MyPageData<TourismProjectTravelNotesWriteVo> tourTourismProjectTravelNotesList = basicToWebServicel.getTourTourismProjectTravelNotesList(tourismTravelNotesWriteDto);

        return ResponseResult.success(tourTourismProjectTravelNotesList);
    }

    /**
     * 列出符合过滤条件的旅游游记列表。(游记页)
     * @return 应答结果对象，包含查询结果集。
     */
    @OperationLog(type = SysOperationLogType.LIST)
    @GetMapping("/travelNotesPageList")
    @SaIgnore
    public ResponseResult<MyPageData<TourismProjectTravelNotesWriteVo>> travelNotesPageList(TourismTravelNotesWriteDto tourismTravelNotesWriteDto) {
        MyPageData<TourismProjectTravelNotesWriteVo> tourTourismProjectTravelNotesList = basicToWebServicel.getTravelNotesPageList(tourismTravelNotesWriteDto);

        return ResponseResult.success(tourTourismProjectTravelNotesList);
    }

    /**
     * 通过旅游游记的id查询游记的详情。
     * @return 应答结果对象，包含查询结果集。
     */
    @OperationLog(type = SysOperationLogType.LIST)
    @GetMapping("/travelNotesDetail")
    @SaIgnore
    public ResponseResult<TourismProjectTravelNotesWriteVo> travelNotesDetail(@RequestParam String id) {

        TourismProjectTravelNotesWriteVo vo = basicToWebServicel.travelNotesDetail(id);

        if(vo != null) {
            vo.setContactCodeConvert("https://v.xiaoyaotravel.com/image/ContactQRCode/tourism.png");
        }
        return ResponseResult.success(vo);
    }

    /**
     * 用户游记收藏
     * param travelNotesId 游记id
     * param type 0取消收藏 1收藏
     * @return 应答结果对象，包含查询结果集。
     */
//    @SaIgnore
    @OperationLog(type = SysOperationLogType.UPDATE)
    @PostMapping("/userCollectTravelNotesUpdate")
    public ResponseResult<Void> userCollectTravelNotesUpdate(@RequestBody TourismCollectDto tourismCollectDto) {
        String errorMessage = MyCommonUtil.getModelValidationError(tourismCollectDto, UpdateGroup.class);
        if (errorMessage != null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED);
        }
        basicToWebServicel.userLikeTravelNotesUpdate(Long.valueOf(tourismCollectDto.getTravelNotesId()),tourismCollectDto.getType());
        return ResponseResult.success();
    }

    /**
     * 用户游记进行点赞
     * param travelNotesId 游记id
     * param type 0取消收藏 1收藏
     * @return 应答结果对象，包含查询结果集。
     */
    @SaIgnore
    @OperationLog(type = SysOperationLogType.UPDATE)
    @PostMapping("/userLikeTravelNotesUpdate")
    public ResponseResult<Void> userLikeTravelNotesUpdate(@RequestBody TourismTravelNotesWriteDto dto) {
        TourismProjectTravelNotesWrite tourismProjectTravelNotesWrite = new TourismProjectTravelNotesWrite();
        tourismProjectTravelNotesWrite.setId(Long.valueOf(dto.getTravelNotesId()));
        TourismProjectTravelNotesWrite tourismProjectTravelNotesWrite1 = tourismProjectTravelNotesWriteService.getOne(tourismProjectTravelNotesWrite);

        tourismProjectTravelNotesWrite1.setLikeCount(tourismProjectTravelNotesWrite1.getLikeCount() + 1);
        tourismProjectTravelNotesWriteService.updateById(tourismProjectTravelNotesWrite1);
        return ResponseResult.success();
    }

    /**
     * 用户是否对该游记进行收藏
     * param travelNotesId 游记id
     * @return 应答结果对象，包含查询结果集。
     */
    @OperationLog(type = SysOperationLogType.LIST)
    @GetMapping("/isCollectTravelNotes")
    public ResponseResult<Boolean> isCollectTravelNotes(@RequestParam String travelNotesId) {
        return ResponseResult.success(basicToWebServicel.isLikeTravelNotes(Long.valueOf(travelNotesId)));
    }

    /**
     * 用户的收藏列表
     *
     * @return 应答结果对象，包含查询结果集。
     */
    @OperationLog(type = SysOperationLogType.LIST)
    @GetMapping("/userCollectTravelNotesList")
    public ResponseResult<MyPageData<TourismProjectTravelNotesWriteVo>> userCollectTravelNotesList(PageDto pageDto) {

        MyOrderParam myOrderParam = new MyOrderParam();
        myOrderParam.add(new MyOrderParam.OrderInfo("updateTime",false,null));
        String orderBy = MyOrderParam.buildOrderBy(myOrderParam, TourUserLikeTravelNotes.class);
        Long userId = TokenData.takeFromRequest().getUserId();
        TourUserLikeTravelNotes filter = new TourUserLikeTravelNotes();
        filter.setUserId(userId);
        if(pageDto.getPageSize() != null && pageDto.getPageNum() != null){
            PageMethod.startPage(pageDto.getPageNum(), pageDto.getPageSize(), true);
        }
        List<TourismProjectTravelNotesWrite> tourUserLikeTravelNotesList = tourUserLikeTravelNotesService.getTourUserLikeTravelNotesWithRelationWriteList(filter, UnmountState.LISTING, orderBy);

        MyPageData<TourismProjectTravelNotesWriteVo> tourismProjectTravelNotesWriteVoMyPageData = MyPageUtil.makeResponseData(tourUserLikeTravelNotesList, TourismProjectTravelNotesWriteVo.class);
        List<TourismProjectTravelNotesWriteVo> dataList = tourismProjectTravelNotesWriteVoMyPageData.getDataList();
        if(CollectionUtils.isNotEmpty(dataList)){
            dataList.stream().forEach(item->{
                item.setTourismUrlsAfterConvert(UrlConvertUtils.urlConvert(applicationConfig.getHostIpPort(), item.getTourismUrl()));
            });
        }

        return ResponseResult.success(tourismProjectTravelNotesWriteVoMyPageData);
    }


    /**
     * 用户游记增加浏览量
     * param travelNotesId 游记id
     * @return 应答结果对象，包含查询结果集。
     */
    @OperationLog(type = SysOperationLogType.ADD)
    @GetMapping("/travelNotesViewCountAdd")
    @SaIgnore
    public ResponseResult<Void> travelNotesViewCountAdd(@RequestParam Long travelNotesId) {
        basicToWebServicel.travelNotesViewCountAdd(travelNotesId);
        return ResponseResult.success();
    }


    /**
     * 游记菜单列表(二维数组)
     * param
     * @return 应答结果对象，包含查询结果集。
     */
    @OperationLog(type = SysOperationLogType.LIST)
    @GetMapping("/travelNotesDirectoryList")
    @SaIgnore
    public ResponseResult<List<TourTravelNotesDirectoryVo>> travelNotesDirectoryList() {

        //设置排序
        MyOrderParam myOrderParam = new MyOrderParam();
        MyOrderParam.OrderInfo orderInfo = new MyOrderParam.OrderInfo();
        orderInfo.setAsc(true);
        orderInfo.setFieldName("showOrder");
        myOrderParam.add(orderInfo);
        String orderBy = MyOrderParam.buildOrderBy(myOrderParam, DirectoryInfo.class);

        //查询一级菜单
        DirectoryInfo directoryInfo = new DirectoryInfo();
        directoryInfo.setParentId(0L);
        directoryInfo.setEnable(1);
        directoryInfo.setDirectoryType(1);
        List<DirectoryInfo> directoryInfoList = directoryInfoService.getDirectoryInfoList(directoryInfo, orderBy);
        //去掉地区的首页区域
        directoryInfoList.removeIf(item -> item.getId().equals(10L));
        //转换并返回数据
        List<TourTravelNotesDirectoryVo> tourTravelNotesDirectoryVoList= new ArrayList<>();
        directoryInfoList.stream().forEach(item->{
            TourTravelNotesDirectoryVo tourTravelNotesDirectoryVo = new TourTravelNotesDirectoryVo();
            tourTravelNotesDirectoryVo.setAreaId(item.getId().toString());
            tourTravelNotesDirectoryVo.setAreaName(item.getMenuName());

            DirectoryInfo directoryInfo1 = new DirectoryInfo();
            directoryInfo1.setEnable(1);
            directoryInfo1.setParentId(item.getId());
            directoryInfo1.setDirectoryType(1);
            List<DirectoryInfo> countryList = directoryInfoService.getDirectoryInfoList(directoryInfo1,orderBy);
            List<TourTravelNotesDirectoryCountryVo> tourTravelNotesDirectoryCountryVoList = new ArrayList<>();
            for(DirectoryInfo country:countryList){
                TourTravelNotesDirectoryCountryVo tourTravelNotesDirectoryCountryVo = new TourTravelNotesDirectoryCountryVo();
                tourTravelNotesDirectoryCountryVo.setCountryId(country.getId().toString());
                tourTravelNotesDirectoryCountryVo.setCountryName(country.getMenuName().toString());
                tourTravelNotesDirectoryCountryVoList.add(tourTravelNotesDirectoryCountryVo);
            }
            tourTravelNotesDirectoryVo.setChildren(tourTravelNotesDirectoryCountryVoList);
            tourTravelNotesDirectoryVoList.add(tourTravelNotesDirectoryVo);
        });
        return ResponseResult.success(tourTravelNotesDirectoryVoList);
    }

    /**
     * 相关项目
     * param travelNotesId 游记id
     * @return 应答结果对象，包含查询结果集。
     */
    @OperationLog(type = SysOperationLogType.LIST)
    @GetMapping("/relateProjectList")
    @SaIgnore
    public ResponseResult<List<TourismProjectVo>> relateProjectList(@RequestParam(required = true) String travelNotesId) {

        TourTravelNotesProjectRelation tourTravelNotesProjectRelation = new TourTravelNotesProjectRelation();
        tourTravelNotesProjectRelation.setTravelNotesId(travelNotesId);
        List<TourTravelNotesProjectRelation> tourTravelNotesProjectRelationList =
                tourTravelNotesProjectRelationService.getTourTravelNotesProjectRelationList(tourTravelNotesProjectRelation, "");
        ArrayList<String> relateProjectList =
                tourTravelNotesProjectRelationList.stream().map(TourTravelNotesProjectRelation::getProjectId).collect(Collectors.toCollection(ArrayList::new));

        if(relateProjectList.size() == 0) {
            return ResponseResult.success(new ArrayList<>());
        }else {
            List<TourismProject> tourismProjectList = tourismProjectService.getInList(new HashSet<>(relateProjectList));
            List<TourismProjectVo> tourismProjectVoList = MyModelUtil.copyCollectionTo(tourismProjectList, TourismProjectVo.class);
            //先把imgUrl由jaon转换为List<FileUrlObject>
            tourismProjectVoList.stream().forEach(item ->
            {
                List<String> urlList = UrlConvertUtils.urlConvert(applicationConfig.getHostIpPort(), item.getHomeHotPicture());
                item.setHomeHotPicturesAfterConvert(urlList);
                List<String> arrayList = UrlConvertUtils.urlConvert(applicationConfig.getHostIpPort(), item.getTourismUrl());
                item.setTourismUrlsAfterConvert(arrayList);
                List<String> arrayList1 = UrlConvertUtils.urlConvert(applicationConfig.getHostIpPort(), item.getTravelNotesBanner());
                item.setTravelNotesBannerAfterConvert(arrayList1);
            });
            return ResponseResult.success(tourismProjectVoList);
        }
    }



    /**
     * 获取点赞数量
     * param travelNotesId 游记id
     * @return 应答结果对象，包含查询结果集。
     */
    @OperationLog(type = SysOperationLogType.LIST)
    @GetMapping("/getLikeCount")
    @SaIgnore
    public ResponseResult<Integer> getLikeCount(@RequestParam(required = true) Long travelNotesId) {

        TourismProjectTravelNotesWrite writeDto = tourismProjectTravelNotesWriteService.getById(travelNotesId);
        Integer likeCount = writeDto.getLikeCount() == null ? 0 : writeDto.getLikeCount();
        return ResponseResult.success(likeCount);
    }
}
