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.*;
import com.tourism.common.core.util.*;
import com.tourism.webadmin.app.website.dto.TourCalcTotalAmountParam;
import com.tourism.webadmin.app.website.dto.TourProjectGroupPurchaseDtoToWebDto;
import com.tourism.webadmin.app.website.vo.TourGroupPurchaseUserVo;
import com.tourism.webadmin.back.model.TourProjectGroupPurchase;
import com.tourism.webadmin.back.model.TourProjectGroupPurchaseDetail;
import com.tourism.webadmin.back.model.TourUser;
import com.tourism.webadmin.back.model.constant.Enable;
import com.tourism.webadmin.back.service.TourOrderService;
import com.tourism.webadmin.back.service.TourProjectGroupPurchaseDetailService;
import com.tourism.webadmin.back.service.TourProjectGroupPurchaseService;
import com.tourism.webadmin.back.service.TourismDatePriceService;
import com.tourism.webadmin.back.vo.TourProjectGroupPurchaseVo;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 拼团设置主表操作控制器类。
 *
 * @author 吃饭睡觉
 * @date 2024-09-06
 */
@Tag(name = "拼团设置主表管理接口")
@Slf4j
@RestController
@RequestMapping("/website/app/tourProjectGroupPurchase")
public class WebsiteProjectGroupPurchaseController {

    @Autowired
    private TourProjectGroupPurchaseService tourProjectGroupPurchaseService;
    @Autowired
    private TourOrderService tourOrderService;
    @Autowired
    private ApplicationConfig applicationConfig;
    @Autowired
    private TourProjectGroupPurchaseDetailService tourProjectGroupPurchaseDetailService;
    @Autowired
    private TourismDatePriceService tourismDatePriceService;

    /**
     * 项目首页热门拼团列表接口。
     *
     * @param dto 过滤对象。
     * @return 应答结果对象，包含查询结果集。
     */
    @SaIgnore
    @GetMapping("/list")
    public ResponseResult<MyPageData<TourProjectGroupPurchaseVo>> list(TourProjectGroupPurchaseDtoToWebDto dto) {
        if (dto != null) {
            PageMethod.startPage(dto.getPageNum(), dto.getPageSize(), dto.getCount());
        }

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        // 判断是不是有出发日期查询条件，如果没传，默认查前后30天的数据
        if(StringUtils.isBlank(dto.getTravelStartTimeStart()) && StringUtils.isBlank(dto.getTravelStartTimeEnd())) {
            Date startDate = MyDateUtil.addDays(new Date(), -30);
            Date endDate = MyDateUtil.addDays(new Date(), 30);

            dto.setTravelStartTimeStart(format.format(startDate));
            dto.setTravelStartTimeEnd(format.format(endDate));
        }
        dto.setEndTimeStart(format.format(new Date()));
        dto.setState(Enable.ENABLE_YES);
        TourProjectGroupPurchase tourProjectGroupPurchaseFilter = MyModelUtil.copyTo(dto, TourProjectGroupPurchase.class);
        MyOrderParam myOrderParam = new MyOrderParam();
        // 如果项目id不为空，说明是项目详情中进行查询的，那么按照出发时间正序排序，如果不为空，则是列表页查询的，按照设定的排序规则进行排序
        if(dto.getProjectId() != null) {
            myOrderParam.add(new MyOrderParam.OrderInfo("travelStartTime",true,null));
        }else {
            myOrderParam.add(new MyOrderParam.OrderInfo("showOrder",true,null));
        }
        String orderBy = MyOrderParam.buildOrderBy(myOrderParam, TourProjectGroupPurchase.class);
        List<TourProjectGroupPurchase> tourProjectGroupPurchaseList =
                tourProjectGroupPurchaseService.getTourProjectGroupPurchaseListWithRelation(tourProjectGroupPurchaseFilter, orderBy);
        // 处理距离拼团结束的时间
        for (TourProjectGroupPurchase entity : tourProjectGroupPurchaseList) {
            int i = MyDateUtil.calculateRelativeDays(entity.getEndTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
            if(i > 0) {
                String s = NumberToChineseConverter.convertToChinese(i);
                entity.setDiffDaysToEnd("还剩" + s + "天失效");
            }
            entity.setImage(UrlConvertUtils.urlConvertSingle(applicationConfig.getHostIpPort(), entity.getImage()));
        }
        return ResponseResult.success(MyPageUtil.makeResponseData(tourProjectGroupPurchaseList, TourProjectGroupPurchaseVo.class));
    }

    /**
     * 查看拼团详情。
     *
     * @param id 指定对象主键Id。
     * @return 应答结果对象，包含对象详情。
     */
    @SaIgnore
    @GetMapping("/view")
    public ResponseResult<TourProjectGroupPurchaseVo> view(@RequestParam Long id) {
        TourProjectGroupPurchase tourProjectGroupPurchase = tourProjectGroupPurchaseService.getByIdWithRelation(id, MyRelationParam.full());
        if (tourProjectGroupPurchase == null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        TourProjectGroupPurchaseVo tourProjectGroupPurchaseVo = MyModelUtil.copyTo(tourProjectGroupPurchase, TourProjectGroupPurchaseVo.class);
//        // 查询阶梯价格详情以计算当前价格
//        TourProjectGroupPurchaseDetail detail = tourProjectGroupPurchaseDetailService.getTourProjectGroupPurchaseDetail(tourProjectGroupPurchase);
//        if(detail != null) {
//            tourProjectGroupPurchaseVo.setNowPrice(detail.getAdultPrice());
//        }else {
//            tourProjectGroupPurchaseVo.setNowPrice(tourProjectGroupPurchaseVo.getOriginalPrice());
//        }
        return ResponseResult.success(tourProjectGroupPurchaseVo);
    }

    /**
     * 查询拼团成功的用户信息，并展示头像、用户昵称和拼团成功的时间
     * @param projectId
     * @return
     */
    @SaIgnore
    @GetMapping("/queryGroupPurchaseUser")
    public ResponseResult<List<TourGroupPurchaseUserVo>> queryGroupPurchaseUser(@RequestParam Long projectId) {
        List<TourUser> tourUserList = tourOrderService.getTourUserListByProjectId(projectId);
        // 把List<TourUser>转为List<TourProjectGroupPurchaseUserVo>
        List<TourGroupPurchaseUserVo> tourGroupPurchaseUserVoList = MyModelUtil.copyCollectionTo(tourUserList, TourGroupPurchaseUserVo.class);
        return ResponseResult.success(tourGroupPurchaseUserVoList);
    }
    /**
     * 根据projectId和出发开始截止时间，查询有拼团活动的日期
     */
    @SaIgnore
    @GetMapping("/queryGroupPurchaseDate")
    public ResponseResult<List<String>> queryGroupPurchaseDate(TourProjectGroupPurchaseDtoToWebDto dto) {
        List<String> dateList = tourProjectGroupPurchaseService.queryUniqueGroupPurchaseDates(dto);
        return ResponseResult.success(dateList);
    }

    @GetMapping("/calcTotalAmount")
    public ResponseResult<Map<String, Object>> calcTotalAmount(TourCalcTotalAmountParam param) {
        return ResponseResult.success(tourProjectGroupPurchaseService.calcTotalAmount(param));
    }


}
