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

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaIgnore;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.page.PageMethod;
import com.tourism.common.additional.config.ApplicationConfig;
import com.tourism.common.additional.utils.MapConvertUtils;
import com.tourism.common.additional.utils.StringUtils;
import com.tourism.common.additional.utils.UrlConvertUtils;
import com.tourism.common.core.annotation.DisableDataFilter;
import com.tourism.common.core.annotation.MyRequestBody;
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.MyRelationParam;
import com.tourism.common.core.object.ResponseResult;
import com.tourism.common.core.util.MyModelUtil;
import com.tourism.common.core.util.MyPageUtil;
import com.tourism.common.log.annotation.OperationLog;
import com.tourism.common.log.model.constant.SysOperationLogType;
import com.tourism.webadmin.app.wechat.dto.PageInfo;
import com.tourism.webadmin.app.wechat.vo.tourism.*;
import com.tourism.webadmin.back.dto.TourTourismTravelNotesContentDto;
import com.tourism.webadmin.back.model.*;
import com.tourism.webadmin.back.service.*;
import com.tourism.webadmin.back.vo.*;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 全球游主页接口。
 *
 * @author huangwen
 * @date 2024/10/22
 */
@Tag(name = "全球游主页接口")
@Slf4j
@RestController
@SaIgnore
@DisableDataFilter
@RequestMapping("/wechat/tourism")
public class WechatTourismIndexController {

   @Autowired
   private TourTourismProjectTravelNotesService tourTourismProjectTravelNotesService;

   @Autowired
   private ApplicationConfig applicationConfig;

   @Autowired
   private DirectoryInfoService directoryInfoService;

   @Autowired
   private TourismProjectService tourismProjectService;

   @Autowired
   private TourismFileService tourismFileService;

   @Autowired
   private TourismContentService tourismContentService;

   @Autowired
   private TourTourismTravelNotesContentService tourTourismTravelNotesContentService;


    /**
     * 全球游热门游记banner4条。
     *
     * @return 应答结果对象。
     */
    @GetMapping("/queryIndexBannerTravelNotes")
    public ResponseResult<List<IndexBannerTravelNoteVo>> queryIndexBannerAndTravelNotes() {

        TourTourismProjectTravelNotes filter = new TourTourismProjectTravelNotes();
        filter.setEnable(1);
        filter.setDataState(1);
        filter.setIsHotspot(1);

        MyOrderParam myOrderParam = new MyOrderParam();
        myOrderParam.add(new MyOrderParam.OrderInfo("hotValue",false,null));
        String orderBy = MyOrderParam.buildOrderBy(myOrderParam, TourTourismProjectTravelNotes.class);

        PageMethod.startPage(1,4,true);
        List<TourTourismProjectTravelNotes> list = tourTourismProjectTravelNotesService.getTourTourismProjectTravelNotesList(filter, orderBy);
        List<IndexBannerTravelNoteVo> dataList = MyPageUtil.makeResponseData(list, IndexBannerTravelNoteVo.class).getDataList();

        dataList.stream().forEach(o->{
            List<String> strings = UrlConvertUtils.urlConvert(applicationConfig.getHostIpPort(), o.getTravelNotesBanner());
            o.setTravelNotesBannerAfterConvert(strings);
        });

        return ResponseResult.success(dataList);
    }

    /**
     * 全球游热门游记id跳转游记。
     *
     * @return 应答结果对象。
     */
    @GetMapping("/queryIndexBannerToTravelNote")
    public ResponseResult<TourTourismProjectTravelNotesVo> queryIndexBannerToTravelNote(@RequestParam @NotNull(message = "首页跳转游记id不能为null") String id) {

        System.out.println(id);
        TourTourismProjectTravelNotes filter = new TourTourismProjectTravelNotes();
        filter.setId(id);
        filter.setEnable(1);
        filter.setDataState(1);

        TourTourismProjectTravelNotes notes = tourTourismProjectTravelNotesService.getTourTourismProjectTravelNotesList(filter, "").get(0);
        TourTourismProjectTravelNotesVo vo = MyModelUtil.copyTo(notes, TourTourismProjectTravelNotesVo.class);
        if (vo.getTourismUrl()!=null){
            List<String> strings = UrlConvertUtils.urlConvert(applicationConfig.getHostIpPort(), vo.getTourismUrl());
            vo.setTourismUrlsAfterConvert(strings);
        }
       if (vo.getTravelNotesBanner()!=null){
           List<String> strings1 = UrlConvertUtils.urlConvert(applicationConfig.getHostIpPort(), vo.getTravelNotesBanner());
           vo.setTravelNotesBannerAfterConvert(strings1);
       }
        return ResponseResult.success(vo);
    }

    /**
     * 某月份最火目的地。
     *
     * @return 应答结果对象。
     */
    @GetMapping("/queryIndexHotDestination")
    public ResponseResult<List<IndexHotDestinationVo>> queryIndexHotDestination() {

        TourismProject filter = new TourismProject();
        filter.setDataState(1);
        filter.setEnable(1);
        filter.setIsHotspot(1);

        MyOrderParam myOrderParam = new MyOrderParam();
        myOrderParam.add(new MyOrderParam.OrderInfo("createTime",false, null));
        myOrderParam.add(new MyOrderParam.OrderInfo("likeCount",false, null));

        String orderBy = MyOrderParam.buildOrderBy(myOrderParam, TourismProject.class);
        List<TourismProject> list = tourismProjectService.getTourismProjectList(filter, orderBy);

        List<IndexHotDestinationVo> dataList = MyModelUtil.copyCollectionTo(list, IndexHotDestinationVo.class);

        dataList.forEach(o->{
            List<String> strings = UrlConvertUtils.urlConvert(applicationConfig.getHostIpPort(), o.getHomeHotPicture());
            o.setHomeHotPicturesAfterConvert(strings);
            DirectoryInfo info = directoryInfoService.getById(o.getBelongTab());
            o.setMenuName(info.getMenuName());
        });

        return  ResponseResult.success(dataList.stream().limit(3).collect(Collectors.toList()));
    }

    /**
     * 首页精选目的地。
     *
     * @return 应答结果对象。
     */
    @GetMapping("/queryIndexWinnowDestination")
    public ResponseResult<IndexHotDestinationVo> queryIndexWinnowDestination() {

        TourismProject filter = new TourismProject();
        filter.setDataState(1);
        filter.setEnable(1);
        filter.setIsWinnowDestination(1);

        List<TourismProject> list = tourismProjectService.getTourismProjectList(filter, "tour_tourism_project.like_count");

        List<IndexHotDestinationVo> dataList = MyModelUtil.copyCollectionTo(list, IndexHotDestinationVo.class);

        IndexHotDestinationVo vo = null;
        if (dataList!=null && !dataList.isEmpty()){
            vo = dataList.get(0);
            List<String> strings = UrlConvertUtils.urlConvert(applicationConfig.getHostIpPort(), vo.getHomeHotPicture());
            vo.setHomeHotPicturesAfterConvert(strings);
            DirectoryInfo menu = directoryInfoService.getById(vo.getBelongTab());
            vo.setMenuName(menu.getMenuName());
        }
        return ResponseResult.success(vo);
    }

    /**
     * 首页热推项目。
     *
     * @return 应答结果对象。
     */
    @GetMapping("/queryIndexHotProject")
    public ResponseResult<List<TourismProjectVo>> queryIndexHotProject() {
        TourismProject filter = new TourismProject();
        filter.setEnable(1);
        filter.setDataState(1);
        filter.setIsHotspot(1);

        MyOrderParam myOrderParam = new MyOrderParam();
        myOrderParam.add(new MyOrderParam.OrderInfo("recommendationRate",true, null));
        myOrderParam.add(new MyOrderParam.OrderInfo("pageViewCount",true, null));
        myOrderParam.add(new MyOrderParam.OrderInfo("likeCount",true, null));
        String orderBy = MyOrderParam.buildOrderBy(myOrderParam, TourismProject.class);

        System.out.println(orderBy);

        PageMethod.startPage(1,2,true);
        List<TourismProject> list = tourismProjectService.getTourismProjectList(filter, orderBy);
        List<TourismProjectVo> voList = MyModelUtil.copyCollectionTo(list, TourismProjectVo.class);
        voList.stream().forEach(o->{
            List<String> strings = UrlConvertUtils.urlConvert(applicationConfig.getHostIpPort(), o.getHomeHotPicture());
            o.setHomeHotPicturesAfterConvert(strings);
        });
        return  ResponseResult.success(voList);
    }

    /**
     * 爆款游记（游记3-6篇）。
     *
     * @return 应答结果对象。
     */
    @GetMapping("/queryIndexHotTravelNote")
    public ResponseResult<Map<String, List<IndexHotProjectTravelNoteVo>>> queryIndexHotTravelNote() {
        //一级
        List<DirectoryInfo> list = directoryInfoService.queryDirectoryNameSub();
        HashMap<String, List<IndexHotProjectTravelNoteVo>> map = new HashMap<>();

        // 遍历一级
        for (DirectoryInfo info : list) {
            // 获取该一级下的二级
            DirectoryInfo filter1 = new DirectoryInfo();
            filter1.setDataState(1);
            filter1.setEnable(1);
            filter1.setIsHotspot(1);
            filter1.setParentId(info.getId());
            List<Long> subIds = directoryInfoService.getDirectoryInfoList(filter1, null).stream().map(DirectoryInfo::getId).collect(Collectors.toList());

            List<IndexHotProjectTravelNoteVo> sumList = new ArrayList<>();

            // 遍历每个二级
            for (Long subId : subIds) {
                TourTourismProjectTravelNotes filter2 = new TourTourismProjectTravelNotes();
                filter2.setBelongTab(subId);
                filter2.setEnable(1);
                filter2.setDataState(1);
                filter2.setIsHotspot(1);

//                MyOrderParam myOrderParam = new MyOrderParam();
//                new MyOrderParam.OrderInfo("tour_tourism_project_travel_notes.hot_value", false, null);
//                String orderBy = MyOrderParam.buildOrderBy(myOrderParam, TourTourismProjectTravelNotes.class);

                List<TourTourismProjectTravelNotes> noteList = tourTourismProjectTravelNotesService.getTourTourismProjectTravelNotesList(filter2, "tour_tourism_project_travel_notes.hot_value");
                if (noteList != null && !noteList.isEmpty()) {
                    List<IndexHotProjectTravelNoteVo> vo = MyModelUtil.copyCollectionTo(noteList, IndexHotProjectTravelNoteVo.class);
                    if (vo != null && !vo.isEmpty()) {
                        vo.forEach(o -> {
                            List<String> strings = UrlConvertUtils.urlConvert(applicationConfig.getHostIpPort(), o.getHomeHotPicture());
                            o.setHomeHotPicturesAfterConvert(strings);
                        });
                        sumList.addAll(vo);
                    }
                }
            }
            map.put(info.getMenuName(), sumList==null||sumList.isEmpty()?null:sumList.stream().limit(6).collect(Collectors.toList()));
        }
        return ResponseResult.success(map);
    }

    /**
     * 首页优质推荐项目。
     *
     * @return 应答结果对象。
     */
    @GetMapping("/queryIndexRecommendationProject")
    public ResponseResult<MyPageData<IndexDestinationProjectVo>> queryIndexRecommendationProject( PageInfo pageInfo) {

        TourismProject filter = new TourismProject();
        filter.setEnable(1);
        filter.setDataState(1);

        MyOrderParam myOrderParam = new MyOrderParam();
        myOrderParam.add(new MyOrderParam.OrderInfo("recommendationRate",true, null));
        myOrderParam.add(new MyOrderParam.OrderInfo("pageViewCount",true, null));
        myOrderParam.add(new MyOrderParam.OrderInfo("likeCount",true, null));
        String orderBy = MyOrderParam.buildOrderBy(myOrderParam, TourismProject.class);


        int pageNum = pageInfo.getPageNum() != null ? pageInfo.getPageNum() : 1;
        int pageSize = pageInfo.getPageSize() != null ? pageInfo.getPageSize() : 8;

        int offset = (pageNum - 1) * pageSize + 2; // 跳过前两条数据

        PageMethod.startPage(offset / pageSize + 1, pageSize);

        List<TourismProject> list = tourismProjectService.getTourismProjectList(filter, orderBy);

        MyPageData<IndexDestinationProjectVo> pageData = MyPageUtil.makeResponseData(list, IndexDestinationProjectVo.class);
        List<IndexDestinationProjectVo> voList = pageData.getDataList();

        voList.stream().forEach(o->{

            TourismFile filter1 = new TourismFile();
            filter1.setDataState(1);
            filter1.setAssociationTableId(o.getId());
            List<TourismFile> fileList = tourismFileService.getTourismFileList(filter1, null);

            fileList.stream().forEach(file->{
                List<String> string = UrlConvertUtils.urlConvert(applicationConfig.getHostIpPort(), file.getFileUrl());
                file.setFileUrlsAfterConvert(string);
            });
            o.setFileList(fileList);

            List<String> strings = UrlConvertUtils.urlConvert(applicationConfig.getHostIpPort(), o.getTourismUrl());
            o.setTourismUrlsAfterConvert(strings);
            List<String> strings1 = UrlConvertUtils.urlConvert(applicationConfig.getHostIpPort(), o.getHomeHotPicture());
            o.setHomeHotPicturesAfterConvert(strings1);
        });
        return ResponseResult.success(pageData);
    }


    /**
     * 旅游项目详情byId。
     *
     * @return 应答结果对象。
     */
    @GetMapping("/queryTourismProjectDetailById")
    public ResponseResult<TourismProjectVo> queryTourismProjectDetailById(@NotNull(message = "所属目录(id)不能为空") String id) {

        TourismProject tourismProject = tourismProjectService.getByIdWithRelation(id, MyRelationParam.full());
        if (tourismProject == null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        TourismProjectVo tourismProjectVo = MyModelUtil.copyTo(tourismProject, TourismProjectVo.class);

        List<String> arrayList = UrlConvertUtils.urlConvert(applicationConfig.getHostIpPort(), tourismProjectVo.getTourismUrl());
        tourismProjectVo.setTourismUrlsAfterConvert(arrayList);
        List<String> arrayList1 = UrlConvertUtils.urlConvert(applicationConfig.getHostIpPort(), tourismProjectVo.getHomeHotPicture());
        tourismProjectVo.setHomeHotPicturesAfterConvert(arrayList1);
        List<String> arrayList2 = UrlConvertUtils.urlConvert(applicationConfig.getHostIpPort(), tourismProjectVo.getTravelNotesBanner());
        tourismProjectVo.setTravelNotesBannerAfterConvert(arrayList2);

        if(tourismProjectVo.getTourismFile() != null){
            // 使用 Jackson 的 ObjectMapper 进行转换
            ObjectMapper objectMapper = new ObjectMapper();
            TourismFile tourismFile = objectMapper.convertValue(tourismProjectVo.getTourismFile(), TourismFile.class);
            if(StringUtils.isNotEmpty(tourismFile.getFileUrl())){
                tourismFile.setFileUrlsAfterConvert(UrlConvertUtils.urlConvert(applicationConfig.getHostIpPort(), tourismFile.getFileUrl()));
                tourismProjectVo.setTourismFile(MapConvertUtils.convertObjectToMap(tourismFile));
            }
        }

        if (tourismProjectVo.getTourismContent()!=null){
            ObjectMapper mapper = new ObjectMapper();
            TourismContent tourismContent = mapper.convertValue(tourismProjectVo.getTourismContent(), TourismContent.class);
            tourismProjectVo.setTourismContent(MapConvertUtils.convertObjectToMap(tourismContent));
        }


        return ResponseResult.success(tourismProjectVo);
    }

    /**
     * 游记详情byId。
     *
     * @return 应答结果对象。
     */
    @GetMapping("/queryTourismNoteDetailById")
    public ResponseResult<TourismNoteDetailVo> queryTourismNoteDetailById(@NotNull(message = "所属目录(id)不能为空") String id) {

        TourismNoteDetailVo detailVo = new TourismNoteDetailVo();
        TourTourismProjectTravelNotes note = tourTourismProjectTravelNotesService.getByIdWithRelation(id, MyRelationParam.normal());

        TourTourismProjectTravelNotesVo vo1 = MyModelUtil.copyTo(note, TourTourismProjectTravelNotesVo.class);
        TourTourismTravelNotesContent filter = new TourTourismTravelNotesContent();
        filter.setAssociationId(id);
        filter.setDataState(1);
        List<TourTourismTravelNotesContent> list = tourTourismTravelNotesContentService.getTourTourismTravelNotesContentList(filter, null);
        if (list!=null&&!list.isEmpty()){
            TourTourismTravelNotesContent content = list.get(0);
            TourTourismTravelNotesContentVo vo = MyModelUtil.copyTo(content, TourTourismTravelNotesContentVo.class);
            detailVo.setTourTourismTravelNotesContentVo(vo);
        }
        detailVo.setTourTourismProjectTravelNotesVo(vo1);
        return ResponseResult.success(detailVo);
    }

}
