package com.tourism.webadmin.back.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaMode;
import com.alibaba.fastjson.JSONObject;
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.vo.*;
import com.tourism.webadmin.back.dto.*;
import com.tourism.webadmin.back.model.*;
import com.tourism.webadmin.back.service.*;
import com.tourism.webadmin.upms.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 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.*;
import java.util.stream.Collectors;

/**
 * 买卖房屋信息管理操作控制器类。
 *
 * @author 吃饭睡觉
 * @date 2024-09-06
 */
@Tag(name = "买卖房屋信息管理管理接口")
@Slf4j
@RestController
@RequestMapping("/admin/app/tourHouseSaleInfo")
public class TourHouseSaleInfoController {

    @Autowired
    private TourHouseFilesService tourHouseFilesService;
    @Autowired
    private TourHouseAdvisorInfoService tourHouseAdvisorInfoService;
    @Autowired
    private ApplicationConfig appConfig;
    @Autowired
    private SessionCacheHelper cacheHelper;
    @Autowired
    private UpDownloaderFactory upDownloaderFactory;
    @Autowired
    private TourHouseSaleInfoService tourHouseSaleInfoService;

    /**
     * 新增买卖房屋信息管理数据，及其关联的从表数据。
     *
     * @param tourHouseSaleInfoDto 新增主表对象。
     * @param tourHouseFilesDtoList 一对多房屋图集信息管理从表列表。
     * @param tourHouseAdvisorRelationDtoList 多对多买卖房与顾问的关联表中间表列表。
     * @return 应答结果对象，包含新增对象主键Id。
     */
    @ApiOperationSupport(ignoreParameters = {
            "tourHouseSaleInfoDto.id",
            "tourHouseSaleInfoDto.searchString",
            "tourHouseSaleInfoDto.totalPriceStart",
            "tourHouseSaleInfoDto.totalPriceEnd",
            "tourHouseSaleInfoDto.areaStart",
            "tourHouseSaleInfoDto.areaEnd",
            "tourHouseSaleInfoDto.currentFloorStart",
            "tourHouseSaleInfoDto.currentFloorEnd",
            "tourHouseSaleInfoDto.houseAgeStart",
            "tourHouseSaleInfoDto.houseAgeEnd",
            "tourHouseSaleInfoDto.averagePriceStart",
            "tourHouseSaleInfoDto.averagePriceEnd",
            "tourHouseSaleInfoDto.totalFloorStart",
            "tourHouseSaleInfoDto.totalFloorEnd",
            "tourHouseSaleInfoDto.yearOfBuildStart",
            "tourHouseSaleInfoDto.yearOfBuildEnd",
            "tourHouseSaleInfoDto.yearOfFinishStart",
            "tourHouseSaleInfoDto.yearOfFinishEnd",
            "tourHouseSaleInfoDto.releaseDateStart",
            "tourHouseSaleInfoDto.releaseDateEnd",
            "tourHouseSaleInfoDto.openingTimeStart",
            "tourHouseSaleInfoDto.openingTimeEnd",
            "tourHouseSaleInfoDto.handingTimeStart",
            "tourHouseSaleInfoDto.handingTimeEnd",
            "tourHouseSaleInfoDto.hotValueStart",
            "tourHouseSaleInfoDto.hotValueEnd"})
    @SaCheckPermission("tourHouseSaleInfo.add")
    @OperationLog(type = SysOperationLogType.ADD)
    @PostMapping("/add")
    public ResponseResult<Long> add(
            @MyRequestBody TourHouseSaleInfoDto tourHouseSaleInfoDto,
            @MyRequestBody List<TourHouseFilesDto> tourHouseFilesDtoList,
            @MyRequestBody List<TourHouseAdvisorRelationDto> tourHouseAdvisorRelationDtoList) {
        ResponseResult<Tuple2<TourHouseSaleInfo, JSONObject>> verifyResult = this.doBusinessDataVerifyAndConvert(
                tourHouseSaleInfoDto, false, tourHouseFilesDtoList, tourHouseAdvisorRelationDtoList);
        if (!verifyResult.isSuccess()) {
            return ResponseResult.errorFrom(verifyResult);
        }
        Tuple2<TourHouseSaleInfo, JSONObject> bizData = verifyResult.getData();
        TourHouseSaleInfo tourHouseSaleInfo = bizData.getFirst();
        tourHouseSaleInfo = tourHouseSaleInfoService.saveNewWithRelation(tourHouseSaleInfo, bizData.getSecond());
        return ResponseResult.success(tourHouseSaleInfo.getId());
    }

    /**
     * 修改买卖房屋信息管理数据，及其关联的从表数据。
     *
     * @param tourHouseSaleInfoDto 修改后的对象。
     * @param tourHouseFilesDtoList 一对多房屋图集信息管理从表列表。
     * @param tourHouseAdvisorRelationDtoList 多对多买卖房与顾问的关联表中间表列表。
     * @return 应答结果对象，包含新增对象主键Id。
     */
    @ApiOperationSupport(ignoreParameters = {
            "tourHouseSaleInfoDto.id",
            "tourHouseSaleInfoDto.searchString",
            "tourHouseSaleInfoDto.totalPriceStart",
            "tourHouseSaleInfoDto.totalPriceEnd",
            "tourHouseSaleInfoDto.areaStart",
            "tourHouseSaleInfoDto.areaEnd",
            "tourHouseSaleInfoDto.currentFloorStart",
            "tourHouseSaleInfoDto.currentFloorEnd",
            "tourHouseSaleInfoDto.houseAgeStart",
            "tourHouseSaleInfoDto.houseAgeEnd",
            "tourHouseSaleInfoDto.averagePriceStart",
            "tourHouseSaleInfoDto.averagePriceEnd",
            "tourHouseSaleInfoDto.totalFloorStart",
            "tourHouseSaleInfoDto.totalFloorEnd",
            "tourHouseSaleInfoDto.yearOfBuildStart",
            "tourHouseSaleInfoDto.yearOfBuildEnd",
            "tourHouseSaleInfoDto.yearOfFinishStart",
            "tourHouseSaleInfoDto.yearOfFinishEnd",
            "tourHouseSaleInfoDto.releaseDateStart",
            "tourHouseSaleInfoDto.releaseDateEnd",
            "tourHouseSaleInfoDto.openingTimeStart",
            "tourHouseSaleInfoDto.openingTimeEnd",
            "tourHouseSaleInfoDto.handingTimeStart",
            "tourHouseSaleInfoDto.handingTimeEnd",
            "tourHouseSaleInfoDto.hotValueStart",
            "tourHouseSaleInfoDto.hotValueEnd"})
    @SaCheckPermission("tourHouseSaleInfo.update")
    @OperationLog(type = SysOperationLogType.UPDATE)
    @PostMapping("/update")
    public ResponseResult<Long> update(
            @MyRequestBody TourHouseSaleInfoDto tourHouseSaleInfoDto,
            @MyRequestBody List<TourHouseFilesDto> tourHouseFilesDtoList,
            @MyRequestBody List<TourHouseAdvisorRelationDto> tourHouseAdvisorRelationDtoList) {
        String errorMessage;
        ResponseResult<Tuple2<TourHouseSaleInfo, JSONObject>> verifyResult = this.doBusinessDataVerifyAndConvert(
                tourHouseSaleInfoDto, true, tourHouseFilesDtoList, tourHouseAdvisorRelationDtoList);
        if (!verifyResult.isSuccess()) {
            return ResponseResult.errorFrom(verifyResult);
        }
        Tuple2<TourHouseSaleInfo, JSONObject> bizData = verifyResult.getData();
        TourHouseSaleInfo originalTourHouseSaleInfo = bizData.getSecond().getObject("originalData", TourHouseSaleInfo.class);
        TourHouseSaleInfo tourHouseSaleInfo = bizData.getFirst();
        if (!tourHouseSaleInfoService.updateWithRelation(tourHouseSaleInfo, originalTourHouseSaleInfo, bizData.getSecond())) {
            errorMessage = "数据验证失败，[TourHouseSaleInfo] 数据不存在!";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        return ResponseResult.success(tourHouseSaleInfo.getId());
    }

    /**
     * 删除买卖房屋信息管理数据。
     *
     * @param id 删除对象主键Id。
     * @return 应答结果对象。
     */
    @SaCheckPermission("tourHouseSaleInfo.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("tourHouseSaleInfo.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 tourHouseSaleInfoDtoFilter 过滤对象。
     * @param tourHouseDevelopersTypeDtoFilter 一对一从表过滤对象。
     * @param tourHouseFilesDtoFilter 一对多从表过滤对象。
     * @param orderParam 排序参数。
     * @param pageParam 分页参数。
     * @return 应答结果对象，包含查询结果集。
     */
    @SaCheckPermission("tourHouseSaleInfo.view")
    @PostMapping("/list")
    public ResponseResult<MyPageData<TourHouseSaleInfoVo>> list(
            @MyRequestBody TourHouseSaleInfoDto tourHouseSaleInfoDtoFilter,
            @MyRequestBody TourHouseDevelopersTypeDto tourHouseDevelopersTypeDtoFilter,
            @MyRequestBody TourHouseFilesDto tourHouseFilesDtoFilter,
            @MyRequestBody MyOrderParam orderParam,
            @MyRequestBody MyPageParam pageParam) {
        if (pageParam != null) {
            PageMethod.startPage(pageParam.getPageNum(), pageParam.getPageSize(), pageParam.getCount());
        }
        TourHouseSaleInfo tourHouseSaleInfoFilter = MyModelUtil.copyTo(tourHouseSaleInfoDtoFilter, TourHouseSaleInfo.class);
        TourHouseDevelopersType tourHouseDevelopersTypeFilter = MyModelUtil.copyTo(tourHouseDevelopersTypeDtoFilter, TourHouseDevelopersType.class);
        TourHouseFiles tourHouseFilesFilter = MyModelUtil.copyTo(tourHouseFilesDtoFilter, TourHouseFiles.class);
        String orderBy = MyOrderParam.buildOrderBy(orderParam, TourHouseSaleInfo.class);
        List<TourHouseSaleInfo> tourHouseSaleInfoList =
                tourHouseSaleInfoService.getTourHouseSaleInfoListWithRelation(tourHouseSaleInfoFilter, tourHouseDevelopersTypeFilter, tourHouseFilesFilter, orderBy);
//        List<TourHouseSaleInfo> tourHouseSaleInfoList =
//                tourHouseSaleInfoService.getTourHouseSaleInfoListWithRelation(tourHouseSaleInfoFilter,orderBy);
        return ResponseResult.success(MyPageUtil.makeResponseData(tourHouseSaleInfoList, TourHouseSaleInfoVo.class));
    }

    /**
     * 导入主表数据列表。
     *
     * @param importFile 上传的文件，目前仅仅支持xlsx和xls两种格式。
     * @return 应答结果对象。
     */
    @SaCheckPermission("tourHouseSaleInfo.import")
    @OperationLog(type = SysOperationLogType.IMPORT)
    @PostMapping("/import")
    public ResponseResult<Void> importBatch(
            @RequestParam Boolean skipHeader,
            @RequestParam("importFile") MultipartFile importFile) throws IOException {
        String filename = ImportUtil.saveImportFile(appConfig.getUploadFileBaseDir(), null, importFile);
        // 这里可以指定需要忽略导入的字段集合。如创建时间、创建人、更新时间、更新人、主键Id和逻辑删除，
        // 以及一些存在缺省值且无需导入的字段。其中主键字段和逻辑删除字段不需要在这里设置，批量插入逻辑会自动处理的。
        Set<String> ignoreFieldSet = new HashSet<>();
        ignoreFieldSet.add("createUserId");
        ignoreFieldSet.add("createTime");
        ignoreFieldSet.add("updateUserId");
        ignoreFieldSet.add("updateTime");
        List<ImportUtil.ImportHeaderInfo> headerInfoList = ImportUtil.makeHeaderInfoList(TourHouseSaleInfo.class, ignoreFieldSet);
        // 下面是导入时需要注意的地方，如果我们缺省生成的代码，与实际情况存在差异，请手动修改。
        // 1. 头信息数据字段，我们只是根据当前的主表实体对象生成了缺省数组，开发者可根据实际情况，对headerInfoList进行修改。
        ImportUtil.ImportHeaderInfo[] headerInfos = headerInfoList.toArray(new ImportUtil.ImportHeaderInfo[]{});
        // 2. 这里需要根据实际情况决定，导入文件中第一行是否为中文头信息，如果是可以跳过。这里我们默认为true。
        // 这里根据自己的实际需求，为doImport的最后一个参数，传递需要进行字典转换的字段集合。
        // 注意，集合中包含需要翻译的Java字段名，如: gradeId。
        Set<String> translatedDictFieldSet = new HashSet<>();
        List<TourHouseSaleInfo> dataList =
                ImportUtil.doImport(headerInfos, skipHeader, filename, TourHouseSaleInfo.class, translatedDictFieldSet);
        CallResult result = tourHouseSaleInfoService.verifyImportList(dataList, translatedDictFieldSet);
        if (!result.isSuccess()) {
            // result中返回了具体的验证失败对象，如果需要返回更加详细的错误，可根据实际情况手动修改。
            return ResponseResult.errorFrom(result);
        }
        tourHouseSaleInfoService.saveNewBatch(dataList, -1);
        return ResponseResult.success();
    }

    /**
     * 导出符合过滤条件的买卖房屋信息管理列表。
     *
     * @param tourHouseSaleInfoDtoFilter 过滤对象。
     * @param tourHouseDevelopersTypeDtoFilter 一对一从表过滤对象。
     * @param tourHouseFilesDtoFilter 一对多从表过滤对象。
     * @param orderParam 排序参数。
     * @throws IOException 文件读写失败。
     */
    @SaCheckPermission("tourHouseSaleInfo.export")
    @OperationLog(type = SysOperationLogType.EXPORT, saveResponse = false)
    @PostMapping("/export")
    public void export(
            @MyRequestBody TourHouseSaleInfoDto tourHouseSaleInfoDtoFilter,
            @MyRequestBody TourHouseDevelopersTypeDto tourHouseDevelopersTypeDtoFilter,
            @MyRequestBody TourHouseFilesDto tourHouseFilesDtoFilter,
            @MyRequestBody MyOrderParam orderParam) throws IOException {
        TourHouseSaleInfo tourHouseSaleInfoFilter = MyModelUtil.copyTo(tourHouseSaleInfoDtoFilter, TourHouseSaleInfo.class);
        TourHouseDevelopersType tourHouseDevelopersTypeFilter = MyModelUtil.copyTo(tourHouseDevelopersTypeDtoFilter, TourHouseDevelopersType.class);
        TourHouseFiles tourHouseFilesFilter = MyModelUtil.copyTo(tourHouseFilesDtoFilter, TourHouseFiles.class);
        String orderBy = MyOrderParam.buildOrderBy(orderParam, TourHouseSaleInfo.class);
        List<TourHouseSaleInfo> resultList =
                tourHouseSaleInfoService.getTourHouseSaleInfoListWithRelation(tourHouseSaleInfoFilter, tourHouseDevelopersTypeFilter, tourHouseFilesFilter, orderBy);
        // 导出文件的标题数组
        // NOTE: 下面的代码中仅仅导出了主表数据，主表聚合计算数据和主表关联字典的数据。
        // 一对一从表数据的导出，可根据需要自行添加。如：headerMap.put("slaveFieldName.xxxField", "标题名称")
        Map<String, String> headerMap = new LinkedHashMap<>(46);
        headerMap.put("id", "主键");
        headerMap.put("areaIdDictMap.name", "所属地区类型");
        headerMap.put("isSaleByLandlordDictMap.name", "是否房东自售 0不是 1是");
        headerMap.put("houseSourceTypeDictMap.name", "房源类型 0新房 1二手房");
        headerMap.put("totalPrice", "总价");
        headerMap.put("officeTypeDictMap.name", "厅室类型");
        headerMap.put("area", "面积");
        headerMap.put("houseTypeDictMap.name", "房屋类型 别墅、公寓...");
        headerMap.put("orientationDictMap.name", "朝向类型");
        headerMap.put("currentFloor", "所在楼层");
        headerMap.put("decorationDictMap.name", "装修类型");
        headerMap.put("houseAge", "房龄");
        headerMap.put("communityName", "楼盘名称/所属小区");
        headerMap.put("address", "地址");
        headerMap.put("averagePrice", "均价");
        headerMap.put("currency", "货币单位");
        headerMap.put("region", "所属区域");
        headerMap.put("coverUrl", "首页封面图");
        headerMap.put("isOnSaleDictMap.name", "是否在售 0待售 1在售");
        headerMap.put("houseTitle", "房屋标题");
        headerMap.put("totalFloor", "总楼层");
        headerMap.put("yearOfBuild", "建造年份");
        headerMap.put("tag", "房屋标签");
        headerMap.put("yearOfFinish", "竣工年份");
        headerMap.put("developersIdDictMap.name", "开发商id");
        headerMap.put("code", "二维码");
        headerMap.put("mobile", "联系电话");
        headerMap.put("propertyRightNature", "产权性质");
        headerMap.put("termOfOwnership", "产权年限");
        headerMap.put("propertyType", "物业类型");
        headerMap.put("housePrincipalLife", "房本年限");
        headerMap.put("isSoleDwellingDictMap.name", "是否唯一住房 0是 1不是");
        headerMap.put("publishingCompany", "发布公司");
        headerMap.put("businessLicense", "营业执照");
        headerMap.put("releaseDate", "发布日期");
        headerMap.put("openingTime", "开盘时间");
        headerMap.put("handingTime", "交房时间");
        headerMap.put("surroundingSupport", "周边配套描述");
        headerMap.put("plotIntroduction", "小区介绍");
        headerMap.put("dataState", "删除标记(1: 正常 -1: 已删除)");
        headerMap.put("hotValue", "热度值");
        headerMap.put("createUserId", "创建人");
        headerMap.put("createTime", "创建时间");
        headerMap.put("updateUserId", "修改人");
        headerMap.put("updateTime", "修改时间");
        headerMap.put("advisorIds", "顾问id");
        ExportUtil.doExport(resultList, headerMap, "tourHouseSaleInfo.xlsx");
    }

    /**
     * 查看指定买卖房屋信息管理对象详情。
     *
     * @param id 指定对象主键Id。
     * @return 应答结果对象，包含对象详情。
     */
    @SaCheckPermission("tourHouseSaleInfo.view")
    @GetMapping("/view")
    public ResponseResult<TourHouseSaleInfoVo> view(@RequestParam Long id) {
        TourHouseSaleInfo tourHouseSaleInfo = tourHouseSaleInfoService.getByIdWithRelation(id, MyRelationParam.full());
        if (tourHouseSaleInfo == null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        TourHouseSaleInfoVo tourHouseSaleInfoVo = MyModelUtil.copyTo(tourHouseSaleInfo, TourHouseSaleInfoVo.class);
        return ResponseResult.success(tourHouseSaleInfoVo);
    }

    /**
     * 列出不与指定买卖房屋信息管理存在多对多关系的 [房屋顾问信息管理] 列表数据。通常用于查看添加新 [房屋顾问信息管理] 对象的候选列表。
     *
     * @param id 主表关联字段。
     * @param tourHouseAdvisorInfoDtoFilter [房屋顾问信息管理] 过滤对象。
     * @param orderParam 排序参数。
     * @param pageParam 分页参数。
     * @return 应答结果对象，返回符合条件的数据列表。
     */
    @SaCheckPermission(value = {"tourHouseSaleInfo.add", "tourHouseSaleInfo.update"}, mode = SaMode.OR)
    @PostMapping("/listNotInTourHouseAdvisorRelation")
    public ResponseResult<MyPageData<TourHouseAdvisorInfoVo>> listNotInTourHouseAdvisorRelation(
            @MyRequestBody Long id,
            @MyRequestBody TourHouseAdvisorInfoDto tourHouseAdvisorInfoDtoFilter,
            @MyRequestBody MyOrderParam orderParam,
            @MyRequestBody MyPageParam pageParam) {
        if (MyCommonUtil.isNotBlankOrNull(id) && !tourHouseSaleInfoService.existId(id)) {
            return ResponseResult.error(ErrorCodeEnum.INVALID_RELATED_RECORD_ID);
        }
        if (pageParam != null) {
            PageMethod.startPage(pageParam.getPageNum(), pageParam.getPageSize(), pageParam.getCount());
        }
        TourHouseAdvisorInfo filter = MyModelUtil.copyTo(tourHouseAdvisorInfoDtoFilter, TourHouseAdvisorInfo.class);
        String orderBy = MyOrderParam.buildOrderBy(orderParam, TourHouseAdvisorInfo.class);
        List<TourHouseAdvisorInfo> tourHouseAdvisorInfoList =
                tourHouseAdvisorInfoService.getNotInTourHouseAdvisorInfoListByHouseId(id, filter, orderBy);
        return ResponseResult.success(MyPageUtil.makeResponseData(tourHouseAdvisorInfoList, TourHouseAdvisorInfoVo.class));
    }

    /**
     * 列出与指定买卖房屋信息管理存在多对多关系的 [房屋顾问信息管理] 列表数据。
     *
     * @param id 主表关联字段。
     * @param tourHouseAdvisorInfoDtoFilter [房屋顾问信息管理] 过滤对象。
     * @param tourHouseAdvisorRelationDtoFilter 多对多关联表过滤对象。
     * @param orderParam 排序参数。
     * @param pageParam 分页参数。
     * @return 应答结果对象，返回符合条件的数据列表。
     */
    @SaCheckPermission("tourHouseSaleInfo.view")
    @PostMapping("/listTourHouseAdvisorRelation")
    public ResponseResult<MyPageData<TourHouseAdvisorInfoVo>> listTourHouseAdvisorRelation(
            @MyRequestBody(required = true) Long id,
            @MyRequestBody TourHouseAdvisorInfoDto tourHouseAdvisorInfoDtoFilter,
            @MyRequestBody TourHouseAdvisorRelationDto tourHouseAdvisorRelationDtoFilter,
            @MyRequestBody MyOrderParam orderParam,
            @MyRequestBody MyPageParam pageParam) {
        if (!tourHouseSaleInfoService.existId(id)) {
            return ResponseResult.error(ErrorCodeEnum.INVALID_RELATED_RECORD_ID);
        }
        if (pageParam != null) {
            PageMethod.startPage(pageParam.getPageNum(), pageParam.getPageSize(), pageParam.getCount());
        }
        TourHouseAdvisorInfo filter = MyModelUtil.copyTo(tourHouseAdvisorInfoDtoFilter, TourHouseAdvisorInfo.class);
        String orderBy = MyOrderParam.buildOrderBy(orderParam, TourHouseAdvisorInfo.class);
        TourHouseAdvisorRelation tourHouseAdvisorRelationFilter =
                MyModelUtil.copyTo(tourHouseAdvisorRelationDtoFilter, TourHouseAdvisorRelation.class);
        List<TourHouseAdvisorInfo> tourHouseAdvisorInfoList =
                tourHouseAdvisorInfoService.getTourHouseAdvisorInfoListByHouseId(id, filter, tourHouseAdvisorRelationFilter, orderBy);
        return ResponseResult.success(MyPageUtil.makeResponseData(tourHouseAdvisorInfoList, TourHouseAdvisorInfoVo.class));
    }

    /**
     * 批量添加买卖房屋信息管理和 [房屋顾问信息管理] 对象的多对多关联关系数据。
     *
     * @param houseId 主表主键Id。
     * @param tourHouseAdvisorRelationDtoList 关联对象列表。
     * @return 应答结果对象。
     */
    @SaCheckPermission("tourHouseSaleInfo.update")
    @OperationLog(type = SysOperationLogType.ADD_M2M)
    @PostMapping("/addTourHouseAdvisorRelation")
    public ResponseResult<Void> addTourHouseAdvisorRelation(
            @MyRequestBody Long houseId,
            @MyRequestBody List<TourHouseAdvisorRelationDto> tourHouseAdvisorRelationDtoList) {
        if (MyCommonUtil.existBlankArgument(houseId, tourHouseAdvisorRelationDtoList)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        Set<Long> advisorIdSet =
                tourHouseAdvisorRelationDtoList.stream().map(TourHouseAdvisorRelationDto::getAdvisorId).collect(Collectors.toSet());
        if (!tourHouseSaleInfoService.existId(houseId)
                || !tourHouseAdvisorInfoService.existUniqueKeyList("id", advisorIdSet)) {
            return ResponseResult.error(ErrorCodeEnum.INVALID_RELATED_RECORD_ID);
        }
        List<TourHouseAdvisorRelation> tourHouseAdvisorRelationList =
                MyModelUtil.copyCollectionTo(tourHouseAdvisorRelationDtoList, TourHouseAdvisorRelation.class);
        tourHouseSaleInfoService.addTourHouseAdvisorRelationList(tourHouseAdvisorRelationList, houseId);
        return ResponseResult.success();
    }

    /**
     * 更新指定买卖房屋信息管理和指定 [房屋顾问信息管理] 的多对多关联数据。
     *
     * @param tourHouseAdvisorRelationDto 对多对中间表对象。
     * @return 应答结果对象。
     */
    @SaCheckPermission("tourHouseSaleInfo.update")
    @OperationLog(type = SysOperationLogType.UPDATE)
    @PostMapping("/updateTourHouseAdvisorRelation")
    public ResponseResult<Void> updateTourHouseAdvisorRelation(
            @MyRequestBody TourHouseAdvisorRelationDto tourHouseAdvisorRelationDto) {
        String errorMessage = MyCommonUtil.getModelValidationError(tourHouseAdvisorRelationDto);
        if (errorMessage != null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, errorMessage);
        }
        TourHouseAdvisorRelation tourHouseAdvisorRelation = MyModelUtil.copyTo(tourHouseAdvisorRelationDto, TourHouseAdvisorRelation.class);
        if (!tourHouseSaleInfoService.updateTourHouseAdvisorRelation(tourHouseAdvisorRelation)) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        return ResponseResult.success();
    }

    /**
     * 显示买卖房屋信息管理和指定 [房屋顾问信息管理] 的多对多关联详情数据。
     *
     * @param houseId 主表主键Id。
     * @param advisorId 从表主键Id。
     * @return 应答结果对象，包括中间表详情。
     */
    @SaCheckPermission("tourHouseSaleInfo.update")
    @GetMapping("/viewTourHouseAdvisorRelation")
    public ResponseResult<TourHouseAdvisorRelationVo> viewTourHouseAdvisorRelation(
            @RequestParam Long houseId, @RequestParam Long advisorId) {
        TourHouseAdvisorRelation tourHouseAdvisorRelation = tourHouseSaleInfoService.getTourHouseAdvisorRelation(houseId, advisorId);
        if (tourHouseAdvisorRelation == null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        TourHouseAdvisorRelationVo tourHouseAdvisorRelationVo = MyModelUtil.copyTo(tourHouseAdvisorRelation, TourHouseAdvisorRelationVo.class);
        return ResponseResult.success(tourHouseAdvisorRelationVo);
    }

    /**
     * 移除指定买卖房屋信息管理和指定 [房屋顾问信息管理] 的多对多关联关系。
     *
     * @param houseId 主表主键Id。
     * @param advisorId 从表主键Id。
     * @return 应答结果对象。
     */
    @SaCheckPermission("tourHouseSaleInfo.update")
    @OperationLog(type = SysOperationLogType.DELETE_M2M)
    @PostMapping("/deleteTourHouseAdvisorRelation")
    public ResponseResult<Void> deleteTourHouseAdvisorRelation(
            @MyRequestBody Long houseId, @MyRequestBody Long advisorId) {
        if (MyCommonUtil.existBlankArgument(houseId, advisorId)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        if (!tourHouseSaleInfoService.removeTourHouseAdvisorRelation(houseId, advisorId)) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        return ResponseResult.success();
    }

    /**
     * 批量移除指定买卖房屋信息管理和指定 [房屋顾问信息管理] 的多对多关联关系。
     *
     * @param houseId 主表主键Id。
     * @param advisorIdList 从表主键Id列表。
     * @return 应答结果对象。
     */
    @SaCheckPermission("tourHouseSaleInfo.update")
    @OperationLog(type = SysOperationLogType.DELETE_M2M_BATCH)
    @PostMapping("/deleteTourHouseAdvisorRelationList")
    public ResponseResult<Void> deleteTourHouseAdvisorRelationList(
            @MyRequestBody Long houseId, @MyRequestBody List<Long> advisorIdList) {
        if (MyCommonUtil.existBlankArgument(houseId, advisorIdList)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        tourHouseSaleInfoService.removeTourHouseAdvisorRelationList(houseId, advisorIdList);
        return ResponseResult.success();
    }

    /**
     * 附件文件下载。
     * 这里将图片和其他类型的附件文件放到不同的父目录下，主要为了便于今后图片文件的迁移。
     *
     * @param id 附件所在记录的主键Id。
     * @param fieldName 附件所属的字段名。
     * @param filename  文件名。如果没有提供该参数，就从当前记录的指定字段中读取。
     * @param asImage   下载文件是否为图片。
     * @param response  Http 应答对象。
     */
    @SaCheckPermission("tourHouseSaleInfo.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 {
                TourHouseSaleInfo tourHouseSaleInfo = tourHouseSaleInfoService.getById(id);
                if (tourHouseSaleInfo == null) {
                    ResponseResult.output(HttpServletResponse.SC_NOT_FOUND);
                    return;
                }
                String fieldJsonData = (String) ReflectUtil.getFieldValue(tourHouseSaleInfo, 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(TourHouseSaleInfo.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(),
                    TourHouseSaleInfo.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("tourHouseSaleInfo.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(TourHouseSaleInfo.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(), TourHouseSaleInfo.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<Tuple2<TourHouseSaleInfo, JSONObject>> doBusinessDataVerifyAndConvert(
            TourHouseSaleInfoDto tourHouseSaleInfoDto,
            boolean forUpdate,
            List<TourHouseFilesDto> tourHouseFilesDtoList,
            List<TourHouseAdvisorRelationDto> tourHouseAdvisorRelationDtoList) {
        ErrorCodeEnum errorCode = ErrorCodeEnum.DATA_VALIDATED_FAILED;
        String errorMessage = MyCommonUtil.getModelValidationError(tourHouseSaleInfoDto, false);
        if (errorMessage != null) {
            return ResponseResult.error(errorCode, errorMessage);
        }
        errorMessage = MyCommonUtil.getModelValidationError(tourHouseFilesDtoList);
        if (errorMessage != null) {
            return ResponseResult.error(errorCode, "参数 [tourHouseFilesDtoList] " + errorMessage);
        }
        errorMessage = MyCommonUtil.getModelValidationError(tourHouseAdvisorRelationDtoList);
        if (errorMessage != null) {
            return ResponseResult.error(errorCode, "参数 [tourHouseAdvisorRelationDtoList] " + errorMessage);
        }
        // 全部关联从表数据的验证和转换
        JSONObject relationData = new JSONObject();
        CallResult verifyResult;
        // 下面是输入参数中，主表关联数据的验证。
        TourHouseSaleInfo tourHouseSaleInfo = MyModelUtil.copyTo(tourHouseSaleInfoDto, TourHouseSaleInfo.class);
        TourHouseSaleInfo originalData = null;
        if (forUpdate && tourHouseSaleInfo != null) {
            originalData = tourHouseSaleInfoService.getById(tourHouseSaleInfo.getId());
            if (originalData == null) {
                return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
            }
            relationData.put("originalData", originalData);
        }
        verifyResult = tourHouseSaleInfoService.verifyRelatedData(tourHouseSaleInfo, originalData);
        if (!verifyResult.isSuccess()) {
            return ResponseResult.errorFrom(verifyResult);
        }
        // 处理主表的一对多关联 [TourHouseFiles]
        List<TourHouseFiles> tourHouseFilesList = MyModelUtil.copyCollectionTo(tourHouseFilesDtoList, TourHouseFiles.class);
        verifyResult = tourHouseFilesService.verifyRelatedData(tourHouseFilesList);
        if (!verifyResult.isSuccess()) {
            return ResponseResult.errorFrom(verifyResult);
        }
        relationData.put("tourHouseFilesList", tourHouseFilesList);
        // 处理主表的多对多关联 [TourHouseAdvisorRelation]
        List<TourHouseAdvisorRelation> tourHouseAdvisorRelationList =
                MyModelUtil.copyCollectionTo(tourHouseAdvisorRelationDtoList, TourHouseAdvisorRelation.class);
        relationData.put("tourHouseAdvisorRelationList", tourHouseAdvisorRelationList);
        return ResponseResult.success(new Tuple2<>(tourHouseSaleInfo, relationData));
    }

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