package com.tourism.webadmin.back.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.util.ReflectUtil;
import com.tourism.common.core.upload.BaseUpDownloader;
import com.tourism.common.core.upload.UpDownloaderFactory;
import com.tourism.common.core.upload.UploadResponseInfo;
import com.tourism.common.core.upload.UploadStoreInfo;
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.dto.*;
import com.tourism.webadmin.back.model.TourismDatePrice;
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.tourism.common.redis.cache.SessionCacheHelper;
import com.tourism.common.additional.config.ApplicationConfig;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.tourism.webadmin.back.vo.TourProjectGroupPurchaseVo;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

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

    @Autowired
    private ApplicationConfig appConfig;
    @Autowired
    private SessionCacheHelper cacheHelper;
    @Autowired
    private UpDownloaderFactory upDownloaderFactory;
    @Autowired
    private TourProjectGroupPurchaseService tourProjectGroupPurchaseService;
    @Autowired
    private TourismDatePriceService tourismDatePriceService;

    /**
     * 新增拼团设置主表数据。
     *
     * @param tourProjectGroupPurchaseDto 新增对象。
     * @return 应答结果对象，包含新增对象主键Id。
     */
    @ApiOperationSupport(ignoreParameters = {
            "tourProjectGroupPurchaseDto.id",
            "tourProjectGroupPurchaseDto.endTimeStart",
            "tourProjectGroupPurchaseDto.endTimeEnd",
            "tourProjectGroupPurchaseDto.travelStartTimeStart",
            "tourProjectGroupPurchaseDto.travelStartTimeEnd",
            "tourProjectGroupPurchaseDto.travelEndTimeStart",
            "tourProjectGroupPurchaseDto.travelEndTimeEnd",
            "tourProjectGroupPurchaseDto.maxCountStart",
            "tourProjectGroupPurchaseDto.maxCountEnd",
            "tourProjectGroupPurchaseDto.adultPriceStart",
            "tourProjectGroupPurchaseDto.adultPriceEnd",
            "tourProjectGroupPurchaseDto.childrenPriceStart",
            "tourProjectGroupPurchaseDto.childrenPriceEnd"})
    @SaCheckPermission("tourProjectGroupPurchase.add")
    @OperationLog(type = SysOperationLogType.ADD)
    @PostMapping("/add")
    public ResponseResult<Long> add(@MyRequestBody TourProjectGroupPurchaseDto tourProjectGroupPurchaseDto) {
        String errorMessage = MyCommonUtil.getModelValidationError(tourProjectGroupPurchaseDto, false);
        if (errorMessage != null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, errorMessage);
        }
        //根据项目id和日期，查询该项目在当天有没有日历价格
        TourismDatePrice tourismDatePrice = new TourismDatePrice();
        tourismDatePrice.setProjectId(String.valueOf(tourProjectGroupPurchaseDto.getProjectId()));
        tourismDatePrice.setDepartureDate(tourProjectGroupPurchaseDto.getTravelStartTime());
        TourismDatePrice tourismDatePriceNowDate = tourismDatePriceService.getOne(tourismDatePrice);
        if(tourismDatePriceNowDate == null){
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, "该项目没有设置对应的日期原价，请先补充对应的日期价格。");
        }
        tourProjectGroupPurchaseDto.setOriginalPrice(tourismDatePriceNowDate.getAdultPrice());
        tourProjectGroupPurchaseDto.setOriginalChildPrice(tourismDatePriceNowDate.getChildrenPrice());
        tourProjectGroupPurchaseDto.setNowPrice(tourismDatePriceNowDate.getAdultPrice());
        tourProjectGroupPurchaseDto.setNowChildPrice(tourismDatePriceNowDate.getChildrenPrice());
        TourProjectGroupPurchase tourProjectGroupPurchase = MyModelUtil.copyTo(tourProjectGroupPurchaseDto, TourProjectGroupPurchase.class);
        // 验证关联Id的数据合法性
        CallResult callResult = tourProjectGroupPurchaseService.verifyRelatedData(tourProjectGroupPurchase, null);
        if (!callResult.isSuccess()) {
            return ResponseResult.errorFrom(callResult);
        }
        tourProjectGroupPurchase = tourProjectGroupPurchaseService.saveNew(tourProjectGroupPurchase);
        return ResponseResult.success(tourProjectGroupPurchase.getId());
    }

    /**
     * 更新拼团设置主表数据。
     *
     * @param tourProjectGroupPurchaseDto 更新对象。
     * @return 应答结果对象。
     */
    @ApiOperationSupport(ignoreParameters = {
            "tourProjectGroupPurchaseDto.endTimeStart",
            "tourProjectGroupPurchaseDto.endTimeEnd",
            "tourProjectGroupPurchaseDto.travelStartTimeStart",
            "tourProjectGroupPurchaseDto.travelStartTimeEnd",
            "tourProjectGroupPurchaseDto.travelEndTimeStart",
            "tourProjectGroupPurchaseDto.travelEndTimeEnd",
            "tourProjectGroupPurchaseDto.maxCountStart",
            "tourProjectGroupPurchaseDto.maxCountEnd",
            "tourProjectGroupPurchaseDto.adultPriceStart",
            "tourProjectGroupPurchaseDto.adultPriceEnd",
            "tourProjectGroupPurchaseDto.childrenPriceStart",
            "tourProjectGroupPurchaseDto.childrenPriceEnd"})
    @SaCheckPermission("tourProjectGroupPurchase.update")
    @OperationLog(type = SysOperationLogType.UPDATE)
    @PostMapping("/update")
    public ResponseResult<Void> update(@MyRequestBody TourProjectGroupPurchaseDto tourProjectGroupPurchaseDto) {
        String errorMessage = MyCommonUtil.getModelValidationError(tourProjectGroupPurchaseDto, true);
        if (errorMessage != null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, errorMessage);
        }
        //根据项目id和日期，查询该项目在当天有没有日历价格
        TourismDatePrice tourismDatePrice = new TourismDatePrice();
        tourismDatePrice.setProjectId(String.valueOf(tourProjectGroupPurchaseDto.getProjectId()));
        tourismDatePrice.setDepartureDate(tourProjectGroupPurchaseDto.getTravelStartTime());
        TourismDatePrice tourismDatePriceNowDate = tourismDatePriceService.getOne(tourismDatePrice);
        TourProjectGroupPurchase tourProjectGroupPurchase = MyModelUtil.copyTo(tourProjectGroupPurchaseDto, TourProjectGroupPurchase.class);
        TourProjectGroupPurchase originalTourProjectGroupPurchase = tourProjectGroupPurchaseService.getById(tourProjectGroupPurchase.getId());
        if (originalTourProjectGroupPurchase == null) {
            // NOTE: 修改下面方括号中的话述
            errorMessage = "数据验证失败，当前 [数据] 并不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        tourProjectGroupPurchase.setOriginalPrice(tourismDatePriceNowDate.getAdultPrice());
        tourProjectGroupPurchase.setOriginalChildPrice(tourismDatePriceNowDate.getChildrenPrice());
        tourProjectGroupPurchase.setNowPrice(tourismDatePriceNowDate.getAdultPrice());
        tourProjectGroupPurchase.setNowChildPrice(tourismDatePriceNowDate.getChildrenPrice());
        // 验证关联Id的数据合法性
        CallResult callResult = tourProjectGroupPurchaseService.verifyRelatedData(tourProjectGroupPurchase, originalTourProjectGroupPurchase);
        if (!callResult.isSuccess()) {
            return ResponseResult.errorFrom(callResult);
        }
        if (!tourProjectGroupPurchaseService.update(tourProjectGroupPurchase, originalTourProjectGroupPurchase)) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        return ResponseResult.success();
    }

    /**
     * 删除拼团设置主表数据。
     *
     * @param id 删除对象主键Id。
     * @return 应答结果对象。
     */
    @SaCheckPermission("tourProjectGroupPurchase.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("tourProjectGroupPurchase.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 tourProjectGroupPurchaseDtoFilter 过滤对象。
     * @param orderParam 排序参数。
     * @param pageParam 分页参数。
     * @return 应答结果对象，包含查询结果集。
     */
    @SaCheckPermission("tourProjectGroupPurchase.view")
    @PostMapping("/list")
    public ResponseResult<MyPageData<TourProjectGroupPurchaseVo>> list(
            @MyRequestBody TourProjectGroupPurchaseDto tourProjectGroupPurchaseDtoFilter,
            @MyRequestBody MyOrderParam orderParam,
            @MyRequestBody MyPageParam pageParam) {
        if (pageParam != null) {
            PageMethod.startPage(pageParam.getPageNum(), pageParam.getPageSize(), pageParam.getCount());
        }
        TourProjectGroupPurchase tourProjectGroupPurchaseFilter = MyModelUtil.copyTo(tourProjectGroupPurchaseDtoFilter, TourProjectGroupPurchase.class);
        String orderBy = MyOrderParam.buildOrderBy(orderParam, TourProjectGroupPurchase.class);
        List<TourProjectGroupPurchase> tourProjectGroupPurchaseList =
                tourProjectGroupPurchaseService.getTourProjectGroupPurchaseListWithRelation(tourProjectGroupPurchaseFilter, orderBy);
        return ResponseResult.success(MyPageUtil.makeResponseData(tourProjectGroupPurchaseList, TourProjectGroupPurchaseVo.class));
    }

    /**
     * 查看指定拼团设置主表对象详情。
     *
     * @param id 指定对象主键Id。
     * @return 应答结果对象，包含对象详情。
     */
    @SaCheckPermission("tourProjectGroupPurchase.view")
    @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);
        return ResponseResult.success(tourProjectGroupPurchaseVo);
    }

    /**
     * 附件文件下载。
     * 这里将图片和其他类型的附件文件放到不同的父目录下，主要为了便于今后图片文件的迁移。
     *
     * @param id 附件所在记录的主键Id。
     * @param fieldName 附件所属的字段名。
     * @param filename  文件名。如果没有提供该参数，就从当前记录的指定字段中读取。
     * @param asImage   下载文件是否为图片。
     * @param response  Http 应答对象。
     */
    @SaCheckPermission("tourProjectGroupPurchase.view")
    @OperationLog(type = SysOperationLogType.DOWNLOAD, saveResponse = false)
    @GetMapping("/download")
    public void download(
            @RequestParam(required = false) Long id,
            @RequestParam String fieldName,
            @RequestParam String filename,
            @RequestParam Boolean asImage,
            HttpServletResponse response) {
        if (MyCommonUtil.existBlankArgument(fieldName, filename, asImage)) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
        // 使用try来捕获异常，是为了保证一旦出现异常可以返回500的错误状态，便于调试。
        // 否则有可能给前端返回的是200的错误码。
        try {
            // 如果请求参数中没有包含主键Id，就判断该文件是否为当前session上传的。
            if (id == null) {
                if (!cacheHelper.existSessionUploadFile(filename)) {
                    ResponseResult.output(HttpServletResponse.SC_FORBIDDEN);
                    return;
                }
            } else {
                TourProjectGroupPurchase tourProjectGroupPurchase = tourProjectGroupPurchaseService.getById(id);
                if (tourProjectGroupPurchase == null) {
                    ResponseResult.output(HttpServletResponse.SC_NOT_FOUND);
                    return;
                }
                String fieldJsonData = (String) ReflectUtil.getFieldValue(tourProjectGroupPurchase, fieldName);
                if (fieldJsonData == null && !cacheHelper.existSessionUploadFile(filename)) {
                    ResponseResult.output(HttpServletResponse.SC_BAD_REQUEST);
                    return;
                }
                if (!BaseUpDownloader.containFile(fieldJsonData, filename)
                        && !cacheHelper.existSessionUploadFile(filename)) {
                    ResponseResult.output(HttpServletResponse.SC_FORBIDDEN);
                    return;
                }
            }
            UploadStoreInfo storeInfo = MyModelUtil.getUploadStoreInfo(TourProjectGroupPurchase.class, fieldName);
            if (!storeInfo.isSupportUpload()) {
                ResponseResult.output(HttpServletResponse.SC_NOT_IMPLEMENTED,
                        ResponseResult.error(ErrorCodeEnum.INVALID_UPLOAD_FIELD));
                return;
            }
            BaseUpDownloader upDownloader = upDownloaderFactory.get(storeInfo.getStoreType());
            upDownloader.doDownload(appConfig.getUploadFileBaseDir(),
                    TourProjectGroupPurchase.class.getSimpleName(), fieldName, filename, asImage, response);
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 文件上传操作。
     *
     * @param fieldName  上传文件名。
     * @param asImage    是否作为图片上传。如果是图片，今后下载的时候无需权限验证。否则就是附件上传，下载时需要权限验证。
     * @param uploadFile 上传文件对象。
     */
    @SaCheckPermission("tourProjectGroupPurchase.view")
    @OperationLog(type = SysOperationLogType.UPLOAD, saveResponse = false)
    @PostMapping("/upload")
    public void upload(
            @RequestParam String fieldName,
            @RequestParam Boolean asImage,
            @RequestParam("uploadFile") MultipartFile uploadFile) throws IOException {
        UploadStoreInfo storeInfo = MyModelUtil.getUploadStoreInfo(TourProjectGroupPurchase.class, fieldName);
        // 这里就会判断参数中指定的字段，是否支持上传操作。
        if (!storeInfo.isSupportUpload()) {
            ResponseResult.output(HttpServletResponse.SC_FORBIDDEN,
                    ResponseResult.error(ErrorCodeEnum.INVALID_UPLOAD_FIELD));
            return;
        }
        // 根据字段注解中的存储类型，通过工厂方法获取匹配的上传下载实现类，从而解耦。
        BaseUpDownloader upDownloader = upDownloaderFactory.get(storeInfo.getStoreType());
        UploadResponseInfo responseInfo = upDownloader.doUpload(null,
                appConfig.getUploadFileBaseDir(), TourProjectGroupPurchase.class.getSimpleName(), fieldName, asImage, uploadFile);
        if (Boolean.TRUE.equals(responseInfo.getUploadFailed())) {
            ResponseResult.output(HttpServletResponse.SC_FORBIDDEN,
                    ResponseResult.error(ErrorCodeEnum.UPLOAD_FAILED, responseInfo.getErrorMessage()));
            return;
        }
        cacheHelper.putSessionUploadFile(responseInfo.getFilename());
        ResponseResult.output(ResponseResult.success(responseInfo));
    }

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