package com.tourism.webadmin.back.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.tourism.common.log.annotation.OperationLog;
import com.tourism.common.log.model.constant.SysOperationLogType;
import com.github.pagehelper.page.PageMethod;
import com.tourism.webadmin.back.model.TourProjectGroupPurchase;
import com.tourism.webadmin.back.vo.*;
import com.tourism.webadmin.back.dto.*;
import com.tourism.webadmin.back.model.*;
import com.tourism.webadmin.back.service.*;
import com.tourism.common.core.object.*;
import com.tourism.common.core.util.*;
import com.tourism.common.core.constant.*;
import com.tourism.common.core.annotation.MyRequestBody;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
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.web.bind.annotation.*;

import java.util.*;

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

    @Autowired
    private TourProjectGroupPurchaseDetailService tourProjectGroupPurchaseDetailService;
    @Autowired
    private TourProjectGroupPurchaseService tourProjectGroupPurchaseService;
    /**
     * 新增拼团设置从表数据。
     *
     * @param tourProjectGroupPurchaseDetailDto 新增对象。
     * @return 应答结果对象，包含新增对象主键Id。
     */
    @ApiOperationSupport(ignoreParameters = {
            "tourProjectGroupPurchaseDetailDto.id",
            "tourProjectGroupPurchaseDetailDto.adultPriceStart",
            "tourProjectGroupPurchaseDetailDto.adultPriceEnd",
            "tourProjectGroupPurchaseDetailDto.childrenPriceStart",
            "tourProjectGroupPurchaseDetailDto.childrenPriceEnd",
            "tourProjectGroupPurchaseDetailDto.minCountStart",
            "tourProjectGroupPurchaseDetailDto.minCountEnd",
            "tourProjectGroupPurchaseDetailDto.maxCountStart",
            "tourProjectGroupPurchaseDetailDto.maxCountEnd"})
    @SaCheckPermission("tourProjectGroupPurchaseDetail.add")
    @OperationLog(type = SysOperationLogType.ADD)
    @PostMapping("/add")
    public ResponseResult<Long> add(@MyRequestBody TourProjectGroupPurchaseDetailDto tourProjectGroupPurchaseDetailDto) {
        String errorMessage = MyCommonUtil.getModelValidationError(tourProjectGroupPurchaseDetailDto, false);
        if (errorMessage != null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, errorMessage);
        }
        //判断拼团的上下限是否超过拼团的最高人数限制
        TourProjectGroupPurchase tourProjectGroupPurchase = new TourProjectGroupPurchase();
        tourProjectGroupPurchase.setCode(tourProjectGroupPurchaseDetailDto.getGroupPurchaseCode());
        TourProjectGroupPurchase tourProjectGroupPurchaseServiceOne = tourProjectGroupPurchaseService.getOne(tourProjectGroupPurchase);
        if(tourProjectGroupPurchaseServiceOne.getMaxCount() < tourProjectGroupPurchaseDetailDto.getMinCount()){
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, "阶梯价格的最低人数不能超过拼团最高人数,请重新填写");
        }
        //判断人数是否存在交集
        TourProjectGroupPurchaseDetail tourProjectGroupPurchaseDetailVerify = new TourProjectGroupPurchaseDetail();
        tourProjectGroupPurchaseDetailVerify.setGroupPurchaseCode(tourProjectGroupPurchaseDetailDto.getGroupPurchaseCode());
        List<TourProjectGroupPurchaseDetail> tourProjectGroupPurchaseDetailList =
                tourProjectGroupPurchaseDetailService.getTourProjectGroupPurchaseDetailList(tourProjectGroupPurchaseDetailVerify, "");
        if(CollectionUtils.isNotEmpty(tourProjectGroupPurchaseDetailList)){
            for(TourProjectGroupPurchaseDetail item:tourProjectGroupPurchaseDetailList){
                if(item.getMaxCount() >= tourProjectGroupPurchaseDetailDto.getMinCount() && tourProjectGroupPurchaseDetailDto.getMaxCount() >= item.getMinCount()){
                    return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, "人数存在交集,请修正后再提交。");
                }
            }
        }
        TourProjectGroupPurchaseDetail tourProjectGroupPurchaseDetail = MyModelUtil.copyTo(tourProjectGroupPurchaseDetailDto, TourProjectGroupPurchaseDetail.class);
        tourProjectGroupPurchaseDetail = tourProjectGroupPurchaseDetailService.saveNew(tourProjectGroupPurchaseDetail);
        return ResponseResult.success(tourProjectGroupPurchaseDetail.getId());
    }

    /**
     * 更新拼团设置从表数据。
     *
     * @param tourProjectGroupPurchaseDetailDto 更新对象。
     * @return 应答结果对象。
     */
    @ApiOperationSupport(ignoreParameters = {
            "tourProjectGroupPurchaseDetailDto.adultPriceStart",
            "tourProjectGroupPurchaseDetailDto.adultPriceEnd",
            "tourProjectGroupPurchaseDetailDto.childrenPriceStart",
            "tourProjectGroupPurchaseDetailDto.childrenPriceEnd",
            "tourProjectGroupPurchaseDetailDto.minCountStart",
            "tourProjectGroupPurchaseDetailDto.minCountEnd",
            "tourProjectGroupPurchaseDetailDto.maxCountStart",
            "tourProjectGroupPurchaseDetailDto.maxCountEnd"})
    @SaCheckPermission("tourProjectGroupPurchaseDetail.update")
    @OperationLog(type = SysOperationLogType.UPDATE)
    @PostMapping("/update")
    public ResponseResult<Void> update(@MyRequestBody TourProjectGroupPurchaseDetailDto tourProjectGroupPurchaseDetailDto) {
        String errorMessage = MyCommonUtil.getModelValidationError(tourProjectGroupPurchaseDetailDto, true);
        if (errorMessage != null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, errorMessage);
        }
        //判断拼团的上下限是否超过拼团的最高人数限制
        TourProjectGroupPurchase tourProjectGroupPurchase = new TourProjectGroupPurchase();
        tourProjectGroupPurchase.setCode(tourProjectGroupPurchaseDetailDto.getGroupPurchaseCode());
        TourProjectGroupPurchase tourProjectGroupPurchaseServiceOne = tourProjectGroupPurchaseService.getOne(tourProjectGroupPurchase);
        if(tourProjectGroupPurchaseServiceOne.getMaxCount() < tourProjectGroupPurchaseDetailDto.getMinCount()){
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, "阶梯价格的最低人数不能超过拼团最高人数,请重新填写");
        }else if(tourProjectGroupPurchaseServiceOne.getMaxCount() < tourProjectGroupPurchaseDetailDto.getMaxCount()){
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, "阶梯价格的最高人数不能超过拼团最高人数,请重新填写");
        }
        //判断人数是否存在交集
        TourProjectGroupPurchaseDetail tourProjectGroupPurchaseDetailVerify = new TourProjectGroupPurchaseDetail();
        tourProjectGroupPurchaseDetailVerify.setGroupPurchaseCode(tourProjectGroupPurchaseDetailDto.getGroupPurchaseCode());
        List<TourProjectGroupPurchaseDetail> tourProjectGroupPurchaseDetailList =
                tourProjectGroupPurchaseDetailService.getTourProjectGroupPurchaseDetailList(tourProjectGroupPurchaseDetailVerify, "");
        if(CollectionUtils.isNotEmpty(tourProjectGroupPurchaseDetailList)){
            for(TourProjectGroupPurchaseDetail item:tourProjectGroupPurchaseDetailList){
                if(item.getMaxCount() >= tourProjectGroupPurchaseDetailDto.getMinCount() && tourProjectGroupPurchaseDetailDto.getMaxCount() >= item.getMinCount()){
                    return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, "人数存在交集,请修正后再提交。");
                }
            }
        }
        TourProjectGroupPurchaseDetail tourProjectGroupPurchaseDetail = MyModelUtil.copyTo(tourProjectGroupPurchaseDetailDto, TourProjectGroupPurchaseDetail.class);
        TourProjectGroupPurchaseDetail originalTourProjectGroupPurchaseDetail = tourProjectGroupPurchaseDetailService.getById(tourProjectGroupPurchaseDetail.getId());
        if (originalTourProjectGroupPurchaseDetail == null) {
            // NOTE: 修改下面方括号中的话述
            errorMessage = "数据验证失败，当前 [数据] 并不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        if (!tourProjectGroupPurchaseDetailService.update(tourProjectGroupPurchaseDetail, originalTourProjectGroupPurchaseDetail)) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        return ResponseResult.success();
    }

    /**
     * 删除拼团设置从表数据。
     *
     * @param id 删除对象主键Id。
     * @return 应答结果对象。
     */
    @SaCheckPermission("tourProjectGroupPurchaseDetail.delete")
    @OperationLog(type = SysOperationLogType.DELETE)
    @PostMapping("/delete")
    public ResponseResult<Void> delete(@MyRequestBody Long id) {
        if (MyCommonUtil.existBlankArgument(id)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        return this.doDelete(id);
    }

    /**
     * 批量删除拼团设置从表数据。
     *
     * @param idList 待删除对象的主键Id列表。
     * @return 应答结果对象。
     */
    @SaCheckPermission("tourProjectGroupPurchaseDetail.delete")
    @OperationLog(type = SysOperationLogType.DELETE_BATCH)
    @PostMapping("/deleteBatch")
    public ResponseResult<Void> deleteBatch(@MyRequestBody List<Long> idList) {
        if (MyCommonUtil.existBlankArgument(idList)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        for (Long id : idList) {
            ResponseResult<Void> responseResult = this.doDelete(id);
            if (!responseResult.isSuccess()) {
                return responseResult;
            }
        }
        return ResponseResult.success();
    }

    /**
     * 列出符合过滤条件的拼团设置从表列表。
     *
     * @param tourProjectGroupPurchaseDetailDtoFilter 过滤对象。
     * @param tourProjectGroupPurchaseDtoFilter 一对多从表过滤对象。
     * @param orderParam 排序参数。
     * @param pageParam 分页参数。
     * @return 应答结果对象，包含查询结果集。
     */
    @SaCheckPermission("tourProjectGroupPurchaseDetail.view")
    @PostMapping("/list")
    public ResponseResult<MyPageData<TourProjectGroupPurchaseDetailVo>> list(
            @MyRequestBody TourProjectGroupPurchaseDetailDto tourProjectGroupPurchaseDetailDtoFilter,
            @MyRequestBody TourProjectGroupPurchaseDto tourProjectGroupPurchaseDtoFilter,
            @MyRequestBody MyOrderParam orderParam,
            @MyRequestBody MyPageParam pageParam) {
        if (pageParam != null) {

            PageMethod.startPage(pageParam.getPageNum(), pageParam.getPageSize(), pageParam.getCount());
        }
        TourProjectGroupPurchaseDetail tourProjectGroupPurchaseDetailFilter = MyModelUtil.copyTo(tourProjectGroupPurchaseDetailDtoFilter, TourProjectGroupPurchaseDetail.class);
        TourProjectGroupPurchase tourProjectGroupPurchaseFilter = MyModelUtil.copyTo(tourProjectGroupPurchaseDtoFilter, TourProjectGroupPurchase.class);
        String orderBy = MyOrderParam.buildOrderBy(orderParam, TourProjectGroupPurchaseDetail.class);
        List<TourProjectGroupPurchaseDetail> tourProjectGroupPurchaseDetailList =
                tourProjectGroupPurchaseDetailService.getTourProjectGroupPurchaseDetailListWithRelation(tourProjectGroupPurchaseDetailFilter, tourProjectGroupPurchaseFilter, orderBy);
        return ResponseResult.success(MyPageUtil.makeResponseData(tourProjectGroupPurchaseDetailList, TourProjectGroupPurchaseDetailVo.class));
    }

    /**
     * 查看指定拼团设置从表对象详情。
     *
     * @param id 指定对象主键Id。
     * @return 应答结果对象，包含对象详情。
     */
    @SaCheckPermission("tourProjectGroupPurchaseDetail.view")
    @GetMapping("/view")
    public ResponseResult<TourProjectGroupPurchaseDetailVo> view(@RequestParam Long id) {
        TourProjectGroupPurchaseDetail tourProjectGroupPurchaseDetail = tourProjectGroupPurchaseDetailService.getByIdWithRelation(id, MyRelationParam.full());
        if (tourProjectGroupPurchaseDetail == null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        TourProjectGroupPurchaseDetailVo tourProjectGroupPurchaseDetailVo = MyModelUtil.copyTo(tourProjectGroupPurchaseDetail, TourProjectGroupPurchaseDetailVo.class);
        return ResponseResult.success(tourProjectGroupPurchaseDetailVo);
    }

    private ResponseResult<Void> doDelete(Long id) {
        String errorMessage;
        // 验证关联Id的数据合法性
        TourProjectGroupPurchaseDetail originalTourProjectGroupPurchaseDetail = tourProjectGroupPurchaseDetailService.getById(id);
        if (originalTourProjectGroupPurchaseDetail == null) {
            // NOTE: 修改下面方括号中的话述
            errorMessage = "数据验证失败，当前 [对象] 并不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        // NOTE: 如果该对象的删除前数据一致性验证和实际需求有偏差，可以根据需求调整验证字段，甚至也可以直接删除下面的验证。
        // 删除前，先主动验证是否存在关联的从表数据。
//        CallResult callResult = tourProjectGroupPurchaseDetailService.verifyRelatedDataBeforeDelete(originalTourProjectGroupPurchaseDetail);
//        if (!callResult.isSuccess()) {
//            return ResponseResult.errorFrom(callResult);
//        }
        if (!tourProjectGroupPurchaseDetailService.remove(id)) {
            errorMessage = "数据操作失败，删除的对象不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        return ResponseResult.success();
    }
}
