package org.dromara.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.system.domain.CommissionTemplate;
import org.dromara.system.domain.bo.CommissionTemplateBo;
import org.dromara.system.domain.vo.CommissionTemplateVo;
import org.dromara.system.mapper.CommissionTemplateMapper;
import org.dromara.system.service.ICommissionTemplateService;
import org.springframework.stereotype.Service;
import java.util.List;
import org.dromara.system.mapper.CommissionSectionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.dromara.system.domain.CommissionSection;

/**
 * 分成比例模板Service实现
 */
@RequiredArgsConstructor
@Service
public class CommissionTemplateServiceImpl extends ServiceImpl<CommissionTemplateMapper, CommissionTemplate> implements ICommissionTemplateService {
    private final CommissionTemplateMapper baseMapper;

    @Autowired
    private CommissionSectionMapper commissionSectionMapper;

    @Override
    public TableDataInfo<CommissionTemplateVo> queryPageList(CommissionTemplateBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<CommissionTemplate> lqw = new LambdaQueryWrapper<>();
        lqw.like(bo.getTemplateName() != null, CommissionTemplate::getTemplateName, bo.getTemplateName());
        lqw.eq(bo.getIsActive() != null, CommissionTemplate::getIsActive, bo.getIsActive());
        Page<CommissionTemplateVo> page = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(page);
    }

    @Override
    public CommissionTemplateVo queryById(Integer id) {
        return baseMapper.selectVoById(id);
    }

    @Override
    public Boolean insertByBo(CommissionTemplateBo bo) {
        CommissionTemplate entity = BeanUtil.toBean(bo, CommissionTemplate.class);
        return baseMapper.insert(entity) > 0;
    }

    @Override
    public Boolean updateByBo(CommissionTemplateBo bo) {
        CommissionTemplate entity = BeanUtil.toBean(bo, CommissionTemplate.class);
        return baseMapper.updateById(entity) > 0;
    }

    @Override
    public Boolean deleteWithValidByIds(List<Integer> ids, Boolean isValid) {
        // 先删除所有关联的区间
        LambdaQueryWrapper<CommissionSection> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(CommissionSection::getTemplateId, ids);
        commissionSectionMapper.delete(wrapper);

        // 再删除模板
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
