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

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.Page;
import com.tourism.common.core.base.dao.BaseDaoMapper;
import com.tourism.common.core.base.service.BaseService;
import com.tourism.common.core.constant.GlobalDeletedFlag;
import com.tourism.common.core.object.CallResult;
import com.tourism.common.core.object.MyRelationParam;
import com.tourism.common.core.util.MyModelUtil;
import com.tourism.common.sequence.wrapper.IdGeneratorWrapper;
import com.tourism.webadmin.back.dao.TourProjectGroupPurchaseDetailMapper;
import com.tourism.webadmin.back.model.TourProjectGroupPurchase;
import com.tourism.webadmin.back.model.TourProjectGroupPurchaseDetail;
import com.tourism.webadmin.back.service.TourProjectGroupPurchaseDetailService;
import com.tourism.webadmin.back.service.TourProjectGroupPurchaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 拼团设置从表数据操作服务类。
 *
 * @author 吃饭睡觉
 * @date 2024-09-06
 */
@Slf4j
@Service("tourProjectGroupPurchaseDetailService")
public class TourProjectGroupPurchaseDetailServiceImpl extends BaseService<TourProjectGroupPurchaseDetail, Long> implements TourProjectGroupPurchaseDetailService {

    @Autowired
    private IdGeneratorWrapper idGenerator;
    @Autowired
    private TourProjectGroupPurchaseDetailMapper tourProjectGroupPurchaseDetailMapper;
    @Autowired
    private TourProjectGroupPurchaseService tourProjectGroupPurchaseService;

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

    @Transactional(rollbackFor = Exception.class)
    @Override
    public TourProjectGroupPurchaseDetail saveNew(TourProjectGroupPurchaseDetail tourProjectGroupPurchaseDetail) {
        tourProjectGroupPurchaseDetailMapper.insert(this.buildDefaultValue(tourProjectGroupPurchaseDetail));
        return tourProjectGroupPurchaseDetail;
    }

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

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

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean remove(Long id) {
        return tourProjectGroupPurchaseDetailMapper.deleteById(id) == 1;
    }

    @Override
    public List<TourProjectGroupPurchaseDetail> getTourProjectGroupPurchaseDetailList(TourProjectGroupPurchaseDetail filter, String orderBy) {
        return tourProjectGroupPurchaseDetailMapper.getTourProjectGroupPurchaseDetailList(filter, orderBy);
    }

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

    @Override
    public CallResult verifyRelatedDataBeforeDelete(TourProjectGroupPurchaseDetail tourProjectGroupPurchaseDetail) {
        TourProjectGroupPurchase tourProjectGroupPurchase = new TourProjectGroupPurchase();
        tourProjectGroupPurchase.setCode(tourProjectGroupPurchaseDetail.getGroupPurchaseCode());
        if (tourProjectGroupPurchaseService.getCountByFilter(tourProjectGroupPurchase) > 0) {
            // NOTE: 可以根据需求修改下面方括号中的提示信息。
            return CallResult.error("数据验证失败，[TourProjectGroupPurchase] 存在关联数据！");
        }
        return CallResult.ok();
    }

    @Override
    public CallResult verifyRelatedData(TourProjectGroupPurchaseDetail tourProjectGroupPurchaseDetail, TourProjectGroupPurchaseDetail originalTourProjectGroupPurchaseDetail) {
        String errorMessageFormat = "数据验证失败，关联的%s并不存在，请刷新后重试！";
        //这里是一对多的验证
        if (this.needToVerify(tourProjectGroupPurchaseDetail, originalTourProjectGroupPurchaseDetail, TourProjectGroupPurchaseDetail::getGroupPurchaseCode)
                && !tourProjectGroupPurchaseService.existOne("code", tourProjectGroupPurchaseDetail.getGroupPurchaseCode())) {
            return CallResult.error(String.format(errorMessageFormat, "关联 拼团设置的id"));
        }
        return CallResult.ok();
    }

    @Override
    public TourProjectGroupPurchaseDetail getTourProjectGroupPurchaseDetail(TourProjectGroupPurchase entity) {
        LambdaQueryWrapper<TourProjectGroupPurchaseDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ge(TourProjectGroupPurchaseDetail::getMinCount, entity.getNowCount());
        queryWrapper.le(TourProjectGroupPurchaseDetail::getMaxCount, entity.getNowCount());
        queryWrapper.eq(TourProjectGroupPurchaseDetail::getGroupPurchaseCode, entity.getCode());

        return tourProjectGroupPurchaseDetailMapper.selectOne(queryWrapper);
    }



    @Override
    public TourProjectGroupPurchase getNowPriceAndNextStagePrice(TourProjectGroupPurchase groupPurchase) {
        // 查询阶梯价格
        TourProjectGroupPurchaseDetail detailFilter = new TourProjectGroupPurchaseDetail();
        detailFilter.setGroupPurchaseCode(groupPurchase.getCode());
        List<TourProjectGroupPurchaseDetail> ladderPriceList = this.getTourProjectGroupPurchaseDetailList(detailFilter, "min_count");
        if(ladderPriceList == null || ladderPriceList.size() == 0) {
            // 如果没查到阶梯价格，那肯定是设置出问题了
            return groupPurchase;
        }
        for(int i = 0; i < ladderPriceList.size(); i++) {
            TourProjectGroupPurchaseDetail detail = ladderPriceList.get(i);
            if(i == 0) {
                // 如果参团的人数少于最低阶梯人数，那么当前价格取原价，下一阶段价格最低阶梯人数的价格
                if(groupPurchase.getNowCount() < detail.getMinCount()) {
                    groupPurchase.setNowPrice(groupPurchase.getOriginalPrice());
                    groupPurchase.setNowChildPrice(groupPurchase.getOriginalPrice());
                    if (i + 1 < ladderPriceList.size()) {
                        // 如果有下个阶段的价格，则赋值
                        groupPurchase.setNextPrice(detail.getAdultPrice());
                        groupPurchase.setNextStageNum(detail.getMinCount() - groupPurchase.getNowCount());
                    }
                }
            }
            // 如果有符合当前人数的阶梯价格，则找下一条数据赋值到下阶段价格和人数字段
            if (groupPurchase.getNowCount() >= detail.getMinCount() && groupPurchase.getNowCount() <= detail.getMaxCount()) {
                groupPurchase.setNowPrice(detail.getAdultPrice());
                groupPurchase.setNowChildPrice(detail.getChildrenPrice());
                if (i + 1 < ladderPriceList.size()) {
                    // 如果有下个阶段的价格，则赋值
                    TourProjectGroupPurchaseDetail nextDetail = ladderPriceList.get(i + 1);
                    groupPurchase.setNextPrice(nextDetail.getAdultPrice());
                    groupPurchase.setNextStageNum(nextDetail.getMinCount() - groupPurchase.getNowCount());
                } else {
                    // 如果当前已经是最后阶段，那么设置下阶段价格为成团价格
                    groupPurchase.setNowPrice(groupPurchase.getAdultPrice());
                    groupPurchase.setNowChildPrice(groupPurchase.getChildrenPrice());
                    groupPurchase.setNextPrice(groupPurchase.getAdultPrice());
                    groupPurchase.setNextStageNum(groupPurchase.getMaxCount() - groupPurchase.getNowCount());
                }
                return groupPurchase;
            } else {
                // 如果当前没找到符合的阶梯价格，那设置肯定是出问题了

            }
        }
        return groupPurchase;
    }

    private TourProjectGroupPurchaseDetail buildDefaultValue(TourProjectGroupPurchaseDetail tourProjectGroupPurchaseDetail) {
        if (tourProjectGroupPurchaseDetail.getId() == null) {
            tourProjectGroupPurchaseDetail.setId(idGenerator.nextLongId());
        }
        MyModelUtil.fillCommonsForInsert(tourProjectGroupPurchaseDetail);
        tourProjectGroupPurchaseDetail.setDataState(GlobalDeletedFlag.NORMAL);
        return tourProjectGroupPurchaseDetail;
    }
}
