package org.dromara.main.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.main.domain.MainBackCategory;
import org.dromara.main.domain.MainBackClause;
import org.dromara.main.domain.bo.MainBackClauseBo;
import org.dromara.main.domain.vo.MainBackClauseVo;
import org.dromara.main.mapper.MainBackCategoryMapper;
import org.dromara.main.mapper.MainBackClauseMapper;
import org.dromara.main.service.IMainBackClauseService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

@RequiredArgsConstructor
@Service
public class MainBackClauseServiceImpl implements IMainBackClauseService {

    private final MainBackClauseMapper baseMapper;

    private final MainBackCategoryMapper categoryMapper;

    /**
     * 查询背调条款分页列表
     */
    @Override
    public TableDataInfo<MainBackClauseVo> queryPageList(MainBackClauseBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<MainBackClause> lqw = buildQueryWrapper(bo);
        Page<MainBackClauseVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询背调条款列表
     */
    @Override
    public List<MainBackClauseVo> queryList(MainBackClauseBo bo) {
        LambdaQueryWrapper<MainBackClause> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 构建查询包装器
     */
    private LambdaQueryWrapper<MainBackClause> buildQueryWrapper(MainBackClauseBo bo) {
        LambdaQueryWrapper<MainBackClause> lqw = Wrappers.lambdaQuery();
        // 关键：根据所属分类 ID 过滤
        lqw.eq(ObjectUtil.isNotNull(bo.getCategoryId()), MainBackClause::getCategoryId, bo.getCategoryId());
        // 模糊查询条款名称
        lqw.like(ObjectUtil.isNotEmpty(bo.getName()), MainBackClause::getName, bo.getName());
        // 根据类型过滤
        lqw.eq(ObjectUtil.isNotEmpty(bo.getType()), MainBackClause::getType, bo.getType());
        // 根据状态过滤
        lqw.eq(ObjectUtil.isNotEmpty(bo.getStatus()), MainBackClause::getStatus, bo.getStatus());
        // 默认按 ID 倒序
        lqw.orderByDesc(MainBackClause::getId);
        return lqw;
    }

    /**
     * 查询详细信息
     */
    @Override
    public MainBackClauseVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 新增
     */
    @Override
    public Boolean insertByBo(MainBackClauseBo bo) {
        MainBackClause add = MapstructUtils.convert(bo, MainBackClause.class);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            updateCategoryPrice(bo.getCategoryId());
        }
        return flag;
    }

    /**
     * 修改
     */
    @Override
    public Boolean updateByBo(MainBackClauseBo bo) {
        MainBackClause update = MapstructUtils.convert(bo, MainBackClause.class);

        boolean flag=baseMapper.updateById(update)>0;
        if(flag) {
            updateCategoryPrice(bo.getCategoryId());
        }
        return flag;
    }

    /**
     * 批量删除
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // 这里可以添加删除前的业务校验逻辑
        }
        boolean flag=baseMapper.deleteBatchIds(ids) > 0;
        if(flag){
            updateCategoryPrice(ids.stream().findFirst().orElse(null));
        }
        return flag;
    }

    private void updateCategoryPrice(Long categoryId) {
        if (categoryId == null) return;

        // 1. 查询该类别下所有的条款
        LambdaQueryWrapper<MainBackClause> lqw = Wrappers.lambdaQuery();
        lqw.eq(MainBackClause::getCategoryId, categoryId);
        List<MainBackClause> clauses = baseMapper.selectList(lqw);

        // 2. 聚合计出总价
        BigDecimal totalPrice = clauses.stream()
            .map(MainBackClause::getPrice)
            .filter(Objects::nonNull)
            .reduce(BigDecimal.ZERO, BigDecimal::add);

        // 3. 更新对应的分类表价格
        MainBackCategory updateCategory = new MainBackCategory();
        updateCategory.setId(categoryId);
        updateCategory.setPrice(totalPrice);
        categoryMapper.updateById(updateCategory);
    }


}
