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.ServiceProduct;
import com.ruoyi.info.service.domain.bo.ServiceProductBo;
import com.ruoyi.info.service.domain.vo.ServiceCategorizeStatisticsVo;
import com.ruoyi.info.service.domain.vo.ServiceProductVo;
import com.ruoyi.info.service.exception.ServiceProductExceptionEnum;
import com.ruoyi.info.service.mapper.ServiceProductMapper;
import com.ruoyi.info.service.service.IServiceCategorizeService;
import com.ruoyi.info.service.service.IServiceProductService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 服务Service业务层处理
 *
 * @author ruoyi
 * @date 2025-09-20
 */
@RequiredArgsConstructor
@Service
public class ServiceProductServiceImpl implements IServiceProductService {

    private final ServiceProductMapper baseMapper;
    private final IServiceCategorizeService serviceCategorizeService;

    /**
     * 查询服务分页
     *
     * @param bo 服务
     * @return 服务
     */
    @Override
    public TableDataInfo<ServiceProductVo> queryPageList(ServiceProductBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ServiceProduct> lqw = buildQueryWrapper(bo);
        Page<ServiceProductVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        result.setRecords(convertList(result.getRecords()));
        return TableDataInfo.build(result);
    }

    /**
     * 查询服务列表
     *
     * @param bo 服务
     * @return 服务
     */
    @Override
    public List<ServiceProductVo> queryList(ServiceProductBo bo) {
        LambdaQueryWrapper<ServiceProduct> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ServiceProduct> buildQueryWrapper(ServiceProductBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ServiceProduct> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getName()), ServiceProduct::getName, bo.getName());
        lqw.eq(bo.getServiceCategorizeId() != null, ServiceProduct::getServiceCategorizeId, bo.getServiceCategorizeId());
        lqw.eq(StringUtils.isNotBlank(bo.getImage()), ServiceProduct::getImage, bo.getImage());
        lqw.eq(bo.getSellingPrice() != null, ServiceProduct::getSellingPrice, bo.getSellingPrice());
        lqw.eq(bo.getOriginalPrice() != null, ServiceProduct::getOriginalPrice, bo.getOriginalPrice());
        lqw.eq(bo.getCostPrice() != null, ServiceProduct::getCostPrice, bo.getCostPrice());
        lqw.eq(bo.getServiceUnit() != null, ServiceProduct::getServiceUnit, bo.getServiceUnit());
        lqw.eq(StringUtils.isNotBlank(bo.getServiceDescription()), ServiceProduct::getServiceDescription, bo.getServiceDescription());
        lqw.eq(StringUtils.isNotBlank(bo.getServiceNotice()), ServiceProduct::getServiceNotice, bo.getServiceNotice());
        lqw.eq(bo.getStatus() != null, ServiceProduct::getStatus, bo.getStatus());
        if(bo.getStartTime() != null) {
            lqw.ge(ServiceProduct::getCreateTime, DateUtil.beginOfDay(bo.getStartTime()));
        }
        if(bo.getEndTime() != null) {
            lqw.le(ServiceProduct::getCreateTime, DateUtil.endOfDay(bo.getEndTime()));
        }
        lqw.orderByDesc(ServiceProduct::getCreateTime);
        return lqw;
    }

    private List<ServiceProductVo> convertList(List<ServiceProductVo> list) {
        return list.stream().map(this::convert).collect(Collectors.toList());
    }

    private ServiceProductVo convert(ServiceProductVo vo){
        if (ObjectUtil.isNull(vo)) {
            return vo;
        }
        vo.setServiceCategorizeName(serviceCategorizeService.queryNameById(vo.getServiceCategorizeId()));
        return vo;
    }

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

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

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

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

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

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

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

    @Override
    public ServiceProductVo queryDelById(Long id) {
        return baseMapper.queryDelById(id);
    }

    @Override
    public List<ServiceCategorizeStatisticsVo> queryServiceCategorizeStatistics() {
        List<ServiceCategorizeStatisticsVo> list = baseMapper.queryServiceCategorizeStatistics();
        return list.stream().map(s -> {
            s.setName(serviceCategorizeService.queryNameById(s.getServiceCategorizeId()));
            return s;
        }).collect(Collectors.toList());
    }

    @Override
    public Long countByCategorizeId(Collection<Long> ids) {
        return baseMapper.selectCount(new LambdaQueryWrapper<ServiceProduct>().in(ServiceProduct::getServiceCategorizeId, ids));
    }

}
