package com.ruoyi.info.service.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.BeanCopyUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.info.service.domain.ServiceCategorize;
import com.ruoyi.info.service.domain.bo.ServiceCategorizeBo;
import com.ruoyi.info.service.domain.vo.ServiceCategorizeVo;
import com.ruoyi.info.service.exception.ServiceCategorizeExceptionEnum;
import com.ruoyi.info.service.mapper.ServiceCategorizeMapper;
import com.ruoyi.info.service.service.IServiceCategorizeService;
import com.ruoyi.info.service.service.IServiceProductService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 服务分类Service业务层处理
 *
 * @author ruoyi
 * @date 2025-09-20
 */
@RequiredArgsConstructor
@Service
public class ServiceCategorizeServiceImpl implements IServiceCategorizeService {

    private final ServiceCategorizeMapper baseMapper;
    @Lazy
    @Resource
    private IServiceProductService serviceProductService;

    /**
     * 查询服务分类分页
     *
     * @param bo 服务分类
     * @return 服务分类
     */
    @Override
    public TableDataInfo<ServiceCategorizeVo> queryPageList(ServiceCategorizeBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ServiceCategorize> lqw = buildQueryWrapper(bo);
        Page<ServiceCategorizeVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询服务分类列表
     *
     * @param bo 服务分类
     * @return 服务分类
     */
    @Override
    public List<ServiceCategorizeVo> queryList(ServiceCategorizeBo bo) {
        LambdaQueryWrapper<ServiceCategorize> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ServiceCategorize> buildQueryWrapper(ServiceCategorizeBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ServiceCategorize> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getName()), ServiceCategorize::getName, bo.getName());
        lqw.eq(bo.getSort() != null, ServiceCategorize::getSort, bo.getSort());
        lqw.eq(bo.getStatus() != null, ServiceCategorize::getStatus, bo.getStatus());
        if(bo.getStartTime() != null) {
            lqw.ge(ServiceCategorize::getCreateTime, DateUtil.beginOfDay(bo.getStartTime()));
        }
        if(bo.getEndTime() != null) {
            lqw.le(ServiceCategorize::getCreateTime, DateUtil.endOfDay(bo.getEndTime()));
        }
        lqw.orderByAsc(ServiceCategorize::getSort);
        return lqw;
    }

    /**
     * 查询服务分类
     *
     * @param id 服务分类主键
     * @return 服务分类
     */
    @Override
    public ServiceCategorizeVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 详情服务分类
     *
     * @param id 服务分类主键
     * @return 服务分类
     */
    @Override
    public ServiceCategorize loadById(Long id, Boolean tw){
        ServiceCategorize info = this.baseMapper.selectById(id);
        if(ObjectUtil.isEmpty(info) && tw){
            throw new ServiceException(ServiceCategorizeExceptionEnum.ServiceCategorize_IS_NOT_EXISTS);
        }
        return info;
    }

    /**
     * 新增服务分类
     *
     * @param bo 服务分类
     * @return 结果
     */
    @Override
    public Boolean insertByBo(ServiceCategorizeBo bo) {
        ServiceCategorize add = BeanUtil.toBean(bo, ServiceCategorize.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改服务分类
     *
     * @param bo 服务分类
     * @return 结果
     */
    @Override
    public Boolean updateByBo(ServiceCategorizeBo bo) {
        ServiceCategorize serviceCategorize = baseMapper.selectById(bo.getId());
        ServiceCategorize update = BeanCopyUtils.copy(bo, serviceCategorize);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(ServiceCategorize entity){
        //TODO 做一些数据校验,如唯一约束
        ServiceCategorize serviceCategorize = baseMapper.selectOne(new LambdaQueryWrapper<ServiceCategorize>().eq(ServiceCategorize::getName, entity.getName()));
        if(serviceCategorize != null && !serviceCategorize.getId().equals(entity.getId())){
            throw new ServiceException(ServiceCategorizeExceptionEnum.ServiceCategorize_NAME_EXISTS);
        }
    }

    /**
     * 批量删除服务分类
     *
     * @param ids 需要删除的服务分类主键
     * @return 结果
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
            Long count = baseMapper.selectCount(new LambdaQueryWrapper<ServiceCategorize>().in(ServiceCategorize::getId, ids).eq(ServiceCategorize::getStatus, true));
            if(count > 0){
                throw new ServiceException(ServiceCategorizeExceptionEnum.ServiceCategorize_EXISTS_ON_SALE);
            }
            count = serviceProductService.countByCategorizeId(ids);
            if(count > 0){
                throw new ServiceException(ServiceCategorizeExceptionEnum.ServiceCategorize_EXISTS_ON_PRODUCT);
            }
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public boolean setStatus(Long id) {
        ServiceCategorize serviceCategorize = loadById(id, true);
        this.baseMapper.update(null, new LambdaUpdateWrapper<ServiceCategorize>()
            .set(ServiceCategorize::getStatus,!serviceCategorize.getStatus())
            .eq(ServiceCategorize::getId,id)
        );
        return true;
    }

    @Override
    public String queryNameById(Long id) {
        return baseMapper.queryNameById(id);
    }

}
