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

import cn.dev33.satoken.annotation.SaIgnore;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.page.PageMethod;
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.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.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.website.dto.TourismProjectToWebDto;
import com.tourism.webadmin.app.website.service.LoginToWebsiteService;
import com.tourism.webadmin.back.dto.TourBookInfoDto;
import com.tourism.webadmin.back.model.DirectoryInfo;
import com.tourism.webadmin.back.model.TourismFile;
import com.tourism.webadmin.back.model.TourismProject;
import com.tourism.webadmin.back.service.TourismProjectService;
import com.tourism.webadmin.back.vo.TourismProjectVo;
import com.tourism.common.additional.config.ApplicationConfig;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static java.util.stream.Collectors.toList;

/**
 * 旅游项目页面接口。
 *
 * @author chenchen
 * @date 2024-09-26
 */
@Tag(name = "小程序旅游板块接口")
@Slf4j
@RestController
@RequestMapping("/wechat/tourProject")
public class TourProjectController {
    @Autowired
    private ApplicationConfig applicationConfig;
    @Autowired
    private TourismProjectService tourismProjectService;
    @Autowired
    private LoginToWebsiteService loginToWebsiteService;
    /**
     * 列出符合过滤条件的旅游项目列表。
     * 接口：旅游页面的接口(searchString: 标题模糊查询;pageNum: 页码;pageSize: 每页大小;count: true)
     * @return 应答结果对象，包含查询结果集。
     */
    @OperationLog(type = SysOperationLogType.LIST)
    @GetMapping("/projectList")
    @SaIgnore
    public ResponseResult<MyPageData<TourismProjectVo>> projectList(TourismProjectToWebDto tourismProjectDtoFilter){
//        if(tourismProjectDtoFilter.getBelongTab() == null){
//            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST,"所属分类(belongTab)不能为空!");
//        }
        //如果belongTab小于1000并且大于10.则表明查询的是一级菜单
        if(tourismProjectDtoFilter.getBelongTab() !=null && tourismProjectDtoFilter.getBelongTab()>=10 && tourismProjectDtoFilter.getBelongTab()<1000){
            DirectoryInfo filter = new DirectoryInfo();
            filter.setParentId(tourismProjectDtoFilter.getBelongTab());
            filter.setEnable(1);
            List<DirectoryInfo> directoryInfoList = tourismProjectService.getDirectoryInfoList(filter, null);
            tourismProjectDtoFilter.setBelongTab(null);
            tourismProjectDtoFilter.setDirectoryInfoIds(directoryInfoList.stream().map(DirectoryInfo::getId).collect(toList()));
        }
        TourismProject tourismProjectFilter = MyModelUtil.copyTo(tourismProjectDtoFilter, TourismProject.class);
        //首页展示的为启用的内容
        tourismProjectFilter.setEnable(1);
        String orderBy = MyOrderParam.buildOrderBy(tourismProjectDtoFilter.getOrderParamList(), TourismProject.class);
        if (tourismProjectDtoFilter.getPageNum() != null && tourismProjectDtoFilter.getPageSize() != null && tourismProjectDtoFilter.getCount() != null) {
            PageMethod.startPage(tourismProjectDtoFilter.getPageNum(), tourismProjectDtoFilter.getPageSize(), tourismProjectDtoFilter.getCount());
        }
        List<TourismProject> tourismProjectList =
                tourismProjectService.getTourismProjectListWithRelation(tourismProjectFilter, orderBy);
        MyPageData<TourismProjectVo> tourismProjectVoMyPageData = MyPageUtil.makeResponseData(tourismProjectList, TourismProjectVo.class);

        List<TourismProjectVo> dataList = tourismProjectVoMyPageData.getDataList();
        //先把imgUrl由jaon转换为List<FileUrlObject>
        dataList.stream().forEach(item ->
        {
            List<String> arrayList2 = UrlConvertUtils.urlConvert(applicationConfig.getHostIpPort(), item.getHomeHotPicture());
            item.setHomeHotPicturesAfterConvert(arrayList2);
            List<String> arrayList3 = UrlConvertUtils.urlConvert(applicationConfig.getHostIpPort(), item.getTourismUrl());
            item.setTourismUrlsAfterConvert(arrayList3);
        });
        return ResponseResult.success(tourismProjectVoMyPageData);
    }

    /**
     * 列出符合过滤条件的旅游项目列表。
     * 接口：旅游页面的接口(searchString: 标题模糊查询;pageNum: 页码;pageSize: 每页大小;count: true)
     * @return 应答结果对象，包含查询结果集。
     */
    @GetMapping("/detail")
    @SaIgnore
    public ResponseResult<TourismProjectVo> detail(@RequestParam Long id){
        TourismProject tourismProject = tourismProjectService.getById(id);
        if (tourismProject == null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        TourismProjectVo tourismProjectVo = MyModelUtil.copyTo(tourismProject, TourismProjectVo.class);
        List<String> arrayList3 = UrlConvertUtils.urlConvert(applicationConfig.getHostIpPort(), tourismProjectVo.getTourismUrl());
        tourismProjectVo.setTourismUrlsAfterConvert(arrayList3);
        List<String> arrayList = UrlConvertUtils.urlConvert(applicationConfig.getHostIpPort(), tourismProjectVo.getHomeHotPicture());
        tourismProjectVo.setHomeHotPicturesAfterConvert(arrayList);
        if(tourismProjectVo.getTourismFile() != null){
            // 使用 Jackson 的 ObjectMapper 进行转换
            ObjectMapper objectMapper = new ObjectMapper();
            TourismFile tourismFile = objectMapper.convertValue(tourismProjectVo.getTourismFile(), TourismFile.class);
            if(StringUtils.isNotEmpty(tourismFile.getFileUrl())){
                List<String> arrayList1 = UrlConvertUtils.urlConvert(applicationConfig.getHostIpPort(), tourismFile.getFileUrl());
                tourismFile.setFileUrlsAfterConvert(arrayList1);
                tourismProjectVo.setTourismFile(MapConvertUtils.convertObjectToMap(tourismFile));
            }
        }
        return ResponseResult.success(tourismProjectVo);
    }

    /**
     * 小程序保存报名信息
     */
    @SaIgnore
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/saveBookInfo")
    public ResponseResult<Void> saveBookInfo(HttpServletRequest request,
                                             @MyRequestBody TourBookInfoDto tourBookInfoDto){
        boolean isSave =
                loginToWebsiteService.saveBookInfo(request, tourBookInfoDto);
        if(!isSave){
            return ResponseResult.error(ErrorCodeEnum.DATA_SAVE_FAILED);
        }
        return ResponseResult.success();
    }
}
