package com.tourism.webadmin.back.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.alibaba.fastjson.JSONObject;
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.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.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/tourHouseAdvisorRelation")
public class TourHouseAdvisorRelationController {

    @Autowired
    private TourHouseAdvisorInfoService tourHouseAdvisorInfoService;
    @Autowired
    private TourHouseSaleInfoService tourHouseSaleInfoService;
    @Autowired
    private TourHouseAdvisorRelationService tourHouseAdvisorRelationService;

    /**
     * 新增买卖房与顾问的关联表数据，及其关联的从表数据。
     *
     * @param tourHouseAdvisorRelationDto 新增主表对象。
     * @param tourHouseSaleInfoDto 一对一买卖房屋信息管理从表Dto。
     * @param tourHouseAdvisorInfoDto 一对一房屋顾问信息管理从表Dto。
     * @return 应答结果对象，包含新增对象主键Id。
     */
    @ApiOperationSupport(ignoreParameters = {"tourHouseAdvisorRelationDto.id"})
    @SaCheckPermission("tourHouseAdvisorRelation.add")
    @OperationLog(type = SysOperationLogType.ADD)
    @PostMapping("/add")
    public ResponseResult<Long> add(
            @MyRequestBody TourHouseAdvisorRelationDto tourHouseAdvisorRelationDto,
            @MyRequestBody TourHouseSaleInfoDto tourHouseSaleInfoDto,
            @MyRequestBody TourHouseAdvisorInfoDto tourHouseAdvisorInfoDto) {
        ResponseResult<Tuple2<TourHouseAdvisorRelation, JSONObject>> verifyResult = this.doBusinessDataVerifyAndConvert(
                tourHouseAdvisorRelationDto, false, tourHouseSaleInfoDto, tourHouseAdvisorInfoDto);
        if (!verifyResult.isSuccess()) {
            return ResponseResult.errorFrom(verifyResult);
        }
        Tuple2<TourHouseAdvisorRelation, JSONObject> bizData = verifyResult.getData();
        TourHouseAdvisorRelation tourHouseAdvisorRelation = bizData.getFirst();
        tourHouseAdvisorRelation = tourHouseAdvisorRelationService.saveNewWithRelation(tourHouseAdvisorRelation, bizData.getSecond());
        return ResponseResult.success(tourHouseAdvisorRelation.getId());
    }

    /**
     * 修改买卖房与顾问的关联表数据，及其关联的从表数据。
     *
     * @param tourHouseAdvisorRelationDto 修改后的对象。
     * @param tourHouseSaleInfoDto 一对一买卖房屋信息管理从表Dto。
     * @param tourHouseAdvisorInfoDto 一对一房屋顾问信息管理从表Dto。
     * @return 应答结果对象，包含新增对象主键Id。
     */
    @ApiOperationSupport(ignoreParameters = {"tourHouseAdvisorRelationDto.id"})
    @SaCheckPermission("tourHouseAdvisorRelation.update")
    @OperationLog(type = SysOperationLogType.UPDATE)
    @PostMapping("/update")
    public ResponseResult<Long> update(
            @MyRequestBody TourHouseAdvisorRelationDto tourHouseAdvisorRelationDto,
            @MyRequestBody TourHouseSaleInfoDto tourHouseSaleInfoDto,
            @MyRequestBody TourHouseAdvisorInfoDto tourHouseAdvisorInfoDto) {
        String errorMessage;
        ResponseResult<Tuple2<TourHouseAdvisorRelation, JSONObject>> verifyResult = this.doBusinessDataVerifyAndConvert(
                tourHouseAdvisorRelationDto, true, tourHouseSaleInfoDto, tourHouseAdvisorInfoDto);
        if (!verifyResult.isSuccess()) {
            return ResponseResult.errorFrom(verifyResult);
        }
        Tuple2<TourHouseAdvisorRelation, JSONObject> bizData = verifyResult.getData();
        TourHouseAdvisorRelation originalTourHouseAdvisorRelation = bizData.getSecond().getObject("originalData", TourHouseAdvisorRelation.class);
        TourHouseAdvisorRelation tourHouseAdvisorRelation = bizData.getFirst();
        if (!tourHouseAdvisorRelationService.updateWithRelation(tourHouseAdvisorRelation, originalTourHouseAdvisorRelation, bizData.getSecond())) {
            errorMessage = "数据验证失败，[TourHouseAdvisorRelation] 数据不存在!";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        return ResponseResult.success(tourHouseAdvisorRelation.getId());
    }

    /**
     * 删除买卖房与顾问的关联表数据。
     *
     * @param id 删除对象主键Id。
     * @return 应答结果对象。
     */
    @SaCheckPermission("tourHouseAdvisorRelation.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("tourHouseAdvisorRelation.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 tourHouseAdvisorRelationDtoFilter 过滤对象。
     * @param orderParam 排序参数。
     * @param pageParam 分页参数。
     * @return 应答结果对象，包含查询结果集。
     */
    @SaCheckPermission("tourHouseAdvisorRelation.view")
    @PostMapping("/list")
    public ResponseResult<MyPageData<TourHouseAdvisorRelationVo>> list(
            @MyRequestBody TourHouseAdvisorRelationDto tourHouseAdvisorRelationDtoFilter,
            @MyRequestBody MyOrderParam orderParam,
            @MyRequestBody MyPageParam pageParam) {
        if (pageParam != null) {
            PageMethod.startPage(pageParam.getPageNum(), pageParam.getPageSize(), pageParam.getCount());
        }
        TourHouseAdvisorRelation tourHouseAdvisorRelationFilter = MyModelUtil.copyTo(tourHouseAdvisorRelationDtoFilter, TourHouseAdvisorRelation.class);
        String orderBy = MyOrderParam.buildOrderBy(orderParam, TourHouseAdvisorRelation.class);
        List<TourHouseAdvisorRelation> tourHouseAdvisorRelationList =
                tourHouseAdvisorRelationService.getTourHouseAdvisorRelationListWithRelation(tourHouseAdvisorRelationFilter, orderBy);
        return ResponseResult.success(MyPageUtil.makeResponseData(tourHouseAdvisorRelationList, TourHouseAdvisorRelationVo.class));
    }

    /**
     * 查看指定买卖房与顾问的关联表对象详情。
     *
     * @param id 指定对象主键Id。
     * @return 应答结果对象，包含对象详情。
     */
    @SaCheckPermission("tourHouseAdvisorRelation.view")
    @GetMapping("/view")
    public ResponseResult<TourHouseAdvisorRelationVo> view(@RequestParam Long id) {
        TourHouseAdvisorRelation tourHouseAdvisorRelation = tourHouseAdvisorRelationService.getByIdWithRelation(id, MyRelationParam.full());
        if (tourHouseAdvisorRelation == null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        TourHouseAdvisorRelationVo tourHouseAdvisorRelationVo = MyModelUtil.copyTo(tourHouseAdvisorRelation, TourHouseAdvisorRelationVo.class);
        return ResponseResult.success(tourHouseAdvisorRelationVo);
    }

    private ResponseResult<Tuple2<TourHouseAdvisorRelation, JSONObject>> doBusinessDataVerifyAndConvert(
            TourHouseAdvisorRelationDto tourHouseAdvisorRelationDto,
            boolean forUpdate,
            TourHouseSaleInfoDto tourHouseSaleInfoDto,
            TourHouseAdvisorInfoDto tourHouseAdvisorInfoDto) {
        ErrorCodeEnum errorCode = ErrorCodeEnum.DATA_VALIDATED_FAILED;
        String errorMessage = MyCommonUtil.getModelValidationError(tourHouseAdvisorRelationDto, false);
        if (errorMessage != null) {
            return ResponseResult.error(errorCode, errorMessage);
        }
        errorMessage = MyCommonUtil.getModelValidationError(tourHouseSaleInfoDto);
        if (errorMessage != null) {
            return ResponseResult.error(errorCode, "参数 [tourHouseSaleInfoDto] " + errorMessage);
        }
        errorMessage = MyCommonUtil.getModelValidationError(tourHouseAdvisorInfoDto);
        if (errorMessage != null) {
            return ResponseResult.error(errorCode, "参数 [tourHouseAdvisorInfoDto] " + errorMessage);
        }
        // 全部关联从表数据的验证和转换
        JSONObject relationData = new JSONObject();
        CallResult verifyResult;
        // 下面是输入参数中，主表关联数据的验证。
        TourHouseAdvisorRelation tourHouseAdvisorRelation = MyModelUtil.copyTo(tourHouseAdvisorRelationDto, TourHouseAdvisorRelation.class);
        TourHouseAdvisorRelation originalData;
        if (forUpdate && tourHouseAdvisorRelation != null) {
            originalData = tourHouseAdvisorRelationService.getById(tourHouseAdvisorRelation.getId());
            if (originalData == null) {
                return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
            }
            relationData.put("originalData", originalData);
        }
        // 处理主表的一对一关联 [TourHouseSaleInfo]
        TourHouseSaleInfo tourHouseSaleInfo = MyModelUtil.copyTo(tourHouseSaleInfoDto, TourHouseSaleInfo.class);
        verifyResult = tourHouseSaleInfoService.verifyRelatedData(tourHouseSaleInfo);
        if (!verifyResult.isSuccess()) {
            return ResponseResult.errorFrom(verifyResult);
        }
        relationData.put("tourHouseSaleInfo", tourHouseSaleInfo);
        // 处理主表的一对一关联 [TourHouseAdvisorInfo]
        TourHouseAdvisorInfo tourHouseAdvisorInfo = MyModelUtil.copyTo(tourHouseAdvisorInfoDto, TourHouseAdvisorInfo.class);
        verifyResult = tourHouseAdvisorInfoService.verifyRelatedData(tourHouseAdvisorInfo);
        if (!verifyResult.isSuccess()) {
            return ResponseResult.errorFrom(verifyResult);
        }
        relationData.put("tourHouseAdvisorInfo", tourHouseAdvisorInfo);
        return ResponseResult.success(new Tuple2<>(tourHouseAdvisorRelation, relationData));
    }

    private ResponseResult<Void> doDelete(Long id) {
        String errorMessage;
        // 验证关联Id的数据合法性
        TourHouseAdvisorRelation originalTourHouseAdvisorRelation = tourHouseAdvisorRelationService.getById(id);
        if (originalTourHouseAdvisorRelation == null) {
            // NOTE: 修改下面方括号中的话述
            errorMessage = "数据验证失败，当前 [对象] 并不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        if (!tourHouseAdvisorRelationService.remove(id)) {
            errorMessage = "数据操作失败，删除的对象不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        return ResponseResult.success();
    }
}
