package com.zsElectric.boot.business.service.impl;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsElectric.boot.business.mapper.CouponMapper;
import com.zsElectric.boot.business.service.CouponService;
import com.zsElectric.boot.business.model.entity.Coupon;
import com.zsElectric.boot.business.model.form.CouponForm;
import com.zsElectric.boot.business.model.query.CouponQuery;
import com.zsElectric.boot.business.model.vo.CouponVO;
import com.zsElectric.boot.business.converter.CouponConverter;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;

/**
 * 优惠劵服务实现类
 *
 * @author zsElectric
 * @since 2025-12-15 09:38
 */
@Service
@RequiredArgsConstructor
public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> implements CouponService {

    private final CouponConverter couponConverter;

    /**
    * 获取优惠劵分页列表
    *
    * @param queryParams 查询参数
    * @return {@link IPage<CouponVO>} 优惠劵分页列表
    */
    @Override
    public IPage<CouponVO> getCouponPage(CouponQuery queryParams) {
        Page<CouponVO> pageVO = this.baseMapper.getCouponPage(
                new Page<>(queryParams.getPageNum(), queryParams.getPageSize()),
                queryParams
        );
        return pageVO;
    }

    /**
     * 获取优惠劵表单数据
     *
     * @param id 优惠劵ID
     * @return 优惠劵表单数据
     */
    @Override
    public CouponForm getCouponFormData(Long id) {
        Coupon entity = this.getById(id);
        return couponConverter.toForm(entity);
    }

    /**
     * 新增优惠劵
     *
     * @param formData 优惠劵表单对象
     * @return 是否新增成功
     */
    @Override
    public boolean saveCoupon(CouponForm formData) {
        Coupon entity = couponConverter.toEntity(formData);
        return this.save(entity);
    }

    /**
     * 更新优惠劵
     *
     * @param id   优惠劵ID
     * @param formData 优惠劵表单对象
     * @return 是否修改成功
     */
    @Override
    public boolean updateCoupon(Long id,CouponForm formData) {
        Coupon entity = couponConverter.toEntity(formData);
        return this.updateById(entity);
    }

    /**
     * 删除优惠劵
     *
     * @param ids 优惠劵ID，多个以英文逗号(,)分割
     * @return 是否删除成功
     */
    @Override
    public boolean deleteCoupons(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的优惠劵数据为空");
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();
        return this.removeByIds(idList);
    }

}
