package com.tourism.webadmin.back.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.tourism.webadmin.back.service.*;
import com.tourism.webadmin.back.dao.*;
import com.tourism.webadmin.back.model.*;
import com.tourism.webadmin.config.DataSourceType;
import com.tourism.common.core.annotation.MyDataSource;
import com.tourism.common.core.base.dao.BaseDaoMapper;
import com.tourism.common.core.constant.GlobalDeletedFlag;
import com.tourism.common.core.object.MyRelationParam;
import com.tourism.common.core.object.CallResult;
import com.tourism.common.core.base.service.BaseService;
import com.tourism.common.core.util.MyModelUtil;
import com.tourism.common.sequence.wrapper.IdGeneratorWrapper;
import com.tourism.common.dict.service.GlobalDictService;
import com.github.pagehelper.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 买卖房屋信息管理数据操作服务类。
 *
 * @author 吃饭睡觉
 * @date 2024-09-06
 */
@Slf4j
//@MyDataSource(DataSourceType.REAL_TEST)
@Service("tourHouseSaleInfoService")
public class TourHouseSaleInfoServiceImpl extends BaseService<TourHouseSaleInfo, Long> implements TourHouseSaleInfoService {

    @Autowired
    private IdGeneratorWrapper idGenerator;
    @Autowired
    private TourHouseSaleInfoMapper tourHouseSaleInfoMapper;
    @Autowired
    private TourHouseAdvisorRelationMapper tourHouseAdvisorRelationMapper;
    @Autowired
    private TourHouseAreaMenuService tourHouseAreaMenuService;
    @Autowired
    private TourHouseDevelopersTypeService tourHouseDevelopersTypeService;
    @Autowired
    private TourHouseFilesService tourHouseFilesService;
    @Autowired
    private GlobalDictService globalDictService;

    /**
     * 返回当前Service的主表Mapper对象。
     *
     * @return 主表Mapper对象。
     */
    @Override
    protected BaseDaoMapper<TourHouseSaleInfo> mapper() {
        return tourHouseSaleInfoMapper;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public TourHouseSaleInfo saveNew(TourHouseSaleInfo tourHouseSaleInfo) {
        tourHouseSaleInfoMapper.insert(this.buildDefaultValue(tourHouseSaleInfo));
        return tourHouseSaleInfo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveNewBatch(List<TourHouseSaleInfo> tourHouseSaleInfoList) {
        if (CollUtil.isNotEmpty(tourHouseSaleInfoList)) {
            tourHouseSaleInfoList.forEach(this::buildDefaultValue);
            tourHouseSaleInfoMapper.insertList(tourHouseSaleInfoList);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveNewBatch(List<TourHouseSaleInfo> tourHouseSaleInfoList, int batchSize) {
        if (CollUtil.isEmpty(tourHouseSaleInfoList)) {
            return;
        }
        if (batchSize <= 0) {
            batchSize = 10000;
        }
        int start = 0;
        do {
            int end = Math.min(tourHouseSaleInfoList.size(), start + batchSize);
            List<TourHouseSaleInfo> subList = tourHouseSaleInfoList.subList(start, end);
            // 如果数据量过大，同时当前表中存在createTime或updateTime等字段，可以考虑在外部创建一次 new Date()，
            // 然后传入buildDefaultValue，这样可以减少对象的创建次数，降低GC，提升效率。橙单之所以没有这样生成，是因为
            // 有些业务场景下需要按照这两个日期字段排序，因此我们只是在这里给出优化建议。
            subList.forEach(this::buildDefaultValue);
            tourHouseSaleInfoMapper.insertList(subList);
            if (end == tourHouseSaleInfoList.size()) {
                break;
            }
            start += batchSize;
        } while (true);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public TourHouseSaleInfo saveNewWithRelation(TourHouseSaleInfo tourHouseSaleInfo, JSONObject relationData) {
        this.saveNew(tourHouseSaleInfo);
        this.saveOrUpdateRelationData(tourHouseSaleInfo, relationData);
        return tourHouseSaleInfo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean update(TourHouseSaleInfo tourHouseSaleInfo, TourHouseSaleInfo originalTourHouseSaleInfo) {
        MyModelUtil.fillCommonsForUpdate(tourHouseSaleInfo, originalTourHouseSaleInfo);
        // 这里重点提示，在执行主表数据更新之前，如果有哪些字段不支持修改操作，请用原有数据对象字段替换当前数据字段。
        UpdateWrapper<TourHouseSaleInfo> uw = this.createUpdateQueryForNullValue(tourHouseSaleInfo, tourHouseSaleInfo.getId());
        return tourHouseSaleInfoMapper.update(tourHouseSaleInfo, uw) == 1;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateWithRelation(
            TourHouseSaleInfo tourHouseSaleInfo, TourHouseSaleInfo originalTourHouseSaleInfo, JSONObject relationData) {
        // tourHouseSaleInfo 为空的时候，无需修改主表数据。
        if (tourHouseSaleInfo != null && !this.update(tourHouseSaleInfo, originalTourHouseSaleInfo)) {
            return false;
        }
        this.saveOrUpdateRelationData(originalTourHouseSaleInfo, relationData);
        return true;
    }

    private void saveOrUpdateRelationData(TourHouseSaleInfo tourHouseSaleInfo, JSONObject relationData) {
        List<TourHouseFiles> tourHouseFilesList =
                relationData.getObject("tourHouseFilesList", new TypeReference<List<TourHouseFiles>>() {});
        List<TourHouseAdvisorRelation> tourHouseAdvisorRelationList =
                relationData.getObject("tourHouseAdvisorRelationList", new TypeReference<List<TourHouseAdvisorRelation>>() {});
        // 对于一对多更新，分为以下三步：
        // 1. 在关联从表中，删除掉与主表字段关联，但是又没有出现在本地更新中的数据。我们将这些数据视为需要删除的数据。
        // 2. 在本次更新数据列表中，如果从表的对象没有主键Id，我们视为新数据，可以批量插入。
        // 3. 在本次更新数据列表中，如果从表的对象存在主键Id，我们视为已有数据，逐条更新。
        if (tourHouseFilesList != null) {
            tourHouseFilesService.updateBatchByTourHouseId(tourHouseSaleInfo.getId(), tourHouseFilesList);
        }
        // 对于多对多更新，因为中间表没有其他业务字段，这里就走先删除后插入的高效处理方式了。
        if (tourHouseAdvisorRelationList != null) {
            TourHouseAdvisorRelation tourHouseAdvisorRelation = new TourHouseAdvisorRelation();
            tourHouseAdvisorRelation.setHouseId(tourHouseSaleInfo.getId());
            tourHouseAdvisorRelationMapper.delete(new QueryWrapper<>(tourHouseAdvisorRelation));
            if (CollUtil.isNotEmpty(tourHouseAdvisorRelationList)) {
                tourHouseAdvisorRelationList.forEach(o -> o.setHouseId(tourHouseSaleInfo.getId()));
                tourHouseAdvisorRelationMapper.insertList(tourHouseAdvisorRelationList);
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean remove(Long id) {
        if (tourHouseSaleInfoMapper.deleteById(id) == 0) {
            return false;
        }
        tourHouseFilesService.removeByTourHouseId(id);
        // 开始删除多对多子表的关联
        TourHouseAdvisorRelation tourHouseAdvisorRelation = new TourHouseAdvisorRelation();
        tourHouseAdvisorRelation.setHouseId(id);
        tourHouseAdvisorRelationMapper.delete(new QueryWrapper<>(tourHouseAdvisorRelation));
        return true;
    }

    @Override
    public List<TourHouseSaleInfo> getTourHouseSaleInfoList(TourHouseSaleInfo filter, String orderBy) {
        return tourHouseSaleInfoMapper.getTourHouseSaleInfoList(filter, orderBy);
    }

    @Override
    public List<TourHouseSaleInfo> getTourHouseSaleInfoListWithRelation(TourHouseSaleInfo filter, TourHouseDevelopersType tourHouseDevelopersTypeFilter, TourHouseFiles tourHouseFilesFilter, String orderBy) {
        List<TourHouseSaleInfo> resultList =
                tourHouseSaleInfoMapper.getTourHouseSaleInfoListEx(filter, tourHouseDevelopersTypeFilter, tourHouseFilesFilter, orderBy);
        // 在缺省生成的代码中，如果查询结果resultList不是Page对象，说明没有分页，那么就很可能是数据导出接口调用了当前方法。
        // 为了避免一次性的大量数据关联，规避因此而造成的系统运行性能冲击，这里手动进行了分批次读取，开发者可按需修改该值。
        int batchSize = resultList instanceof Page ? 0 : 1000;
        this.buildRelationForDataList(resultList, MyRelationParam.normal(), batchSize);
        return resultList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addTourHouseAdvisorRelationList(List<TourHouseAdvisorRelation> tourHouseAdvisorRelationList, Long houseId) {
        for (TourHouseAdvisorRelation tourHouseAdvisorRelation : tourHouseAdvisorRelationList) {
            tourHouseAdvisorRelation.setHouseId(houseId);
            tourHouseAdvisorRelationMapper.insert(tourHouseAdvisorRelation);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateTourHouseAdvisorRelation(TourHouseAdvisorRelation tourHouseAdvisorRelation) {
        TourHouseAdvisorRelation filter = new TourHouseAdvisorRelation();
        filter.setHouseId(tourHouseAdvisorRelation.getHouseId());
        filter.setAdvisorId(tourHouseAdvisorRelation.getAdvisorId());
        UpdateWrapper<TourHouseAdvisorRelation> uw =
                BaseService.createUpdateQueryForNullValue(tourHouseAdvisorRelation, TourHouseAdvisorRelation.class);
        uw.setEntity(filter);
        return tourHouseAdvisorRelationMapper.update(tourHouseAdvisorRelation, uw) > 0;
    }

    @Override
    public TourHouseAdvisorRelation getTourHouseAdvisorRelation(Long houseId, Long advisorId) {
        TourHouseAdvisorRelation filter = new TourHouseAdvisorRelation();
        filter.setHouseId(houseId);
        filter.setAdvisorId(advisorId);
        return tourHouseAdvisorRelationMapper.selectOne(new QueryWrapper<>(filter));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean removeTourHouseAdvisorRelation(Long houseId, Long advisorId) {
        TourHouseAdvisorRelation filter = new TourHouseAdvisorRelation();
        filter.setHouseId(houseId);
        filter.setAdvisorId(advisorId);
        return tourHouseAdvisorRelationMapper.delete(new QueryWrapper<>(filter)) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void removeTourHouseAdvisorRelationList(Long houseId, List<Long> advisorIdList) {
        LambdaQueryWrapper<TourHouseAdvisorRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TourHouseAdvisorRelation::getHouseId, houseId);
        queryWrapper.in(TourHouseAdvisorRelation::getAdvisorId, advisorIdList);
        tourHouseAdvisorRelationMapper.delete(queryWrapper);
    }

    @Override
    public CallResult verifyImportList(List<TourHouseSaleInfo> dataList, Set<String> ignoreFieldSet) {
        CallResult callResult;
        if (!CollUtil.contains(ignoreFieldSet, "isSaleByLandlord")) {
            callResult = verifyImportForConstDict(dataList, "isSaleByLandlordDictMap", TourHouseSaleInfo::getIsSaleByLandlord);
            if (!callResult.isSuccess()) {
                return callResult;
            }
        }
        if (!CollUtil.contains(ignoreFieldSet, "isOnSale")) {
            callResult = verifyImportForConstDict(dataList, "isOnSaleDictMap", TourHouseSaleInfo::getIsOnSale);
            if (!callResult.isSuccess()) {
                return callResult;
            }
        }
        if (!CollUtil.contains(ignoreFieldSet, "isSoleDwelling")) {
            callResult = verifyImportForConstDict(dataList, "isSoleDwellingDictMap", TourHouseSaleInfo::getIsSoleDwelling);
            if (!callResult.isSuccess()) {
                return callResult;
            }
        }
        if (!CollUtil.contains(ignoreFieldSet, "houseSourceType")) {
            callResult = verifyImportForGlobalDict(dataList, "houseSourceTypeDictMap", TourHouseSaleInfo::getHouseSourceType);
            if (!callResult.isSuccess()) {
                return callResult;
            }
        }
        if (!CollUtil.contains(ignoreFieldSet, "officeType")) {
            callResult = verifyImportForGlobalDict(dataList, "officeTypeDictMap", TourHouseSaleInfo::getOfficeType);
            if (!callResult.isSuccess()) {
                return callResult;
            }
        }
        if (!CollUtil.contains(ignoreFieldSet, "houseType")) {
            callResult = verifyImportForGlobalDict(dataList, "houseTypeDictMap", TourHouseSaleInfo::getHouseType);
            if (!callResult.isSuccess()) {
                return callResult;
            }
        }
        if (!CollUtil.contains(ignoreFieldSet, "orientation")) {
            callResult = verifyImportForGlobalDict(dataList, "orientationDictMap", TourHouseSaleInfo::getOrientation);
            if (!callResult.isSuccess()) {
                return callResult;
            }
        }
        if (!CollUtil.contains(ignoreFieldSet, "decoration")) {
            callResult = verifyImportForGlobalDict(dataList, "decorationDictMap", TourHouseSaleInfo::getDecoration);
            if (!callResult.isSuccess()) {
                return callResult;
            }
        }
        if (!CollUtil.contains(ignoreFieldSet, "areaId")) {
            callResult = verifyImportForDatasourceDict(dataList, "areaIdDictMap", TourHouseSaleInfo::getAreaId);
            if (!callResult.isSuccess()) {
                return callResult;
            }
        }
        if (!CollUtil.contains(ignoreFieldSet, "developersId")) {
            callResult = verifyImportForDatasourceDict(dataList, "developersIdDictMap", TourHouseSaleInfo::getDevelopersId);
            if (!callResult.isSuccess()) {
                return callResult;
            }
        }
        return CallResult.ok();
    }

    @Override
    public CallResult verifyRelatedData(TourHouseSaleInfo tourHouseSaleInfo, TourHouseSaleInfo originalTourHouseSaleInfo) {
        String errorMessageFormat = "数据验证失败，关联的%s并不存在，请刷新后重试！";
        //这里是基于字典的验证。
        if (this.needToVerify(tourHouseSaleInfo, originalTourHouseSaleInfo, TourHouseSaleInfo::getAreaId)
                && !tourHouseAreaMenuService.existId(tourHouseSaleInfo.getAreaId())) {
            return CallResult.error(String.format(errorMessageFormat, "所属地区类型"));
        }
        //这里是基于字典的验证。
        if (this.needToVerify(tourHouseSaleInfo, originalTourHouseSaleInfo, TourHouseSaleInfo::getHouseSourceType)
                && !globalDictService.existDictItemFromCache("HouseSourceType", tourHouseSaleInfo.getHouseSourceType())) {
            return CallResult.error(String.format(errorMessageFormat, "房源类型 0新房 1二手房"));
        }
        //这里是基于字典的验证。
        if (this.needToVerify(tourHouseSaleInfo, originalTourHouseSaleInfo, TourHouseSaleInfo::getOfficeType)
                && !globalDictService.existDictItemFromCache("OfficeType", tourHouseSaleInfo.getOfficeType())) {
            return CallResult.error(String.format(errorMessageFormat, "厅室类型"));
        }
        //这里是基于字典的验证。
        if (this.needToVerify(tourHouseSaleInfo, originalTourHouseSaleInfo, TourHouseSaleInfo::getHouseType)
                && !globalDictService.existDictItemFromCache("HouseType", tourHouseSaleInfo.getHouseType())) {
            return CallResult.error(String.format(errorMessageFormat, "房屋类型 别墅、公寓..."));
        }
        //这里是基于字典的验证。
        if (this.needToVerify(tourHouseSaleInfo, originalTourHouseSaleInfo, TourHouseSaleInfo::getOrientation)
                && !globalDictService.existDictItemFromCache("Orientation", tourHouseSaleInfo.getOrientation())) {
            return CallResult.error(String.format(errorMessageFormat, "朝向类型"));
        }
        //这里是基于字典的验证。
        if (this.needToVerify(tourHouseSaleInfo, originalTourHouseSaleInfo, TourHouseSaleInfo::getDecoration)
                && !globalDictService.existDictItemFromCache("Decoration", tourHouseSaleInfo.getDecoration())) {
            return CallResult.error(String.format(errorMessageFormat, "装修类型"));
        }
        //这里是基于字典的验证。
        if (this.needToVerify(tourHouseSaleInfo, originalTourHouseSaleInfo, TourHouseSaleInfo::getDevelopersId)
                && !tourHouseDevelopersTypeService.existId(tourHouseSaleInfo.getDevelopersId())) {
            return CallResult.error(String.format(errorMessageFormat, "开发商id"));
        }
        return CallResult.ok();
    }

    private TourHouseSaleInfo buildDefaultValue(TourHouseSaleInfo tourHouseSaleInfo) {
        if (tourHouseSaleInfo.getId() == null) {
            tourHouseSaleInfo.setId(idGenerator.nextLongId());
        }
        MyModelUtil.fillCommonsForInsert(tourHouseSaleInfo);
        tourHouseSaleInfo.setDataState(GlobalDeletedFlag.NORMAL);
        MyModelUtil.setDefaultValue(tourHouseSaleInfo, "hotValue", 0);
        return tourHouseSaleInfo;
    }

    @Override
    public List<TourHouseSaleInfo> getTourHouseSaleInfoListWithArea(TourHouseSaleInfo filter,String orderBy) {

        List<TourHouseSaleInfo> resultList = tourHouseSaleInfoMapper.getTourHouseSaleInfoListWithArea(filter,orderBy);
        // 在缺省生成的代码中，如果查询结果resultList不是Page对象，说明没有分页，那么就很可能是数据导出接口调用了当前方法。
        // 为了避免一次性的大量数据关联，规避因此而造成的系统运行性能冲击，这里手动进行了分批次读取，开发者可按需修改该值。
        int batchSize = resultList instanceof Page ? 0 : 1000;
        this.buildRelationForDataList(resultList, MyRelationParam.normal(), batchSize);
        return resultList;
    }
}
