package com.czg.service.account.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.czg.account.dto.song.ShopSongAddDTO;
import com.czg.account.dto.song.ShopSongEditDTO;
import com.czg.config.RedisCst;
import com.czg.exception.CzgException;
import com.czg.sa.StpKit;
import com.czg.service.RedisService;
import com.czg.utils.CzgRandomUtils;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.czg.account.entity.ShopSong;
import com.czg.account.service.ShopSongService;
import com.czg.service.account.mapper.ShopSongMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

/**
 * 点歌-歌曲表 服务层实现。
 *
 * @author zs
 * @since 2025-03-01
 */
@Service
public class ShopSongServiceImpl extends ServiceImpl<ShopSongMapper, ShopSong> implements ShopSongService {
    @Resource
    private RedisService redisService;

    @Override
    public Boolean add(Long shopId, ShopSongAddDTO shopSongAddDTO) {
        ShopSong shopSong = BeanUtil.copyProperties(shopSongAddDTO, ShopSong.class);
        shopSong.setShopId(shopId);
        return save(shopSong);
    }

    @Override
    public Boolean edit(Long shopId, ShopSongEditDTO shopSongEditDTO) {
        ShopSong shopSong = getOne(new QueryWrapper().eq(ShopSong::getShopId, StpKit.USER.getShopId()).eq(ShopSong::getId, shopSongEditDTO.getId()));
        if (shopSong == null) {
            throw new CzgException("歌曲列表不存在");
        }

        BeanUtil.copyProperties(shopSongEditDTO, shopSong);
        return updateById(shopSong);
    }

    @Override
    public String getSongUrl(Long shopId) {
        String code;
        String key = RedisCst.getSongUrlKey(shopId);
        if (redisService.hasKey(key)) {
            code = (String) redisService.get(key);
        } else {
            code = CzgRandomUtils.randomString(12);
            redisService.set(key, code);
        }
        return code;
    }
}
