package com.jeesharp.business.modules.mall.service.impl;

import com.jeesharp.business.modules.mall.entity.MallSpuSpec;
import com.jeesharp.business.modules.mall.mapper.MallSpuSpecMapper;
import com.jeesharp.business.modules.mall.service.MallSpuSpecService;
import com.jeesharp.business.modules.mall.vo.MallSpuSpecQueryVO;
import com.jeesharp.framework.mybatis.core.service.CrudService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**
 * SPU规格关联 Service 实现类
 */
@Service
@Transactional(readOnly = true)
public class MallSpuSpecServiceImpl extends CrudService<MallSpuSpecMapper, MallSpuSpec, MallSpuSpecQueryVO> implements MallSpuSpecService {

    private static final String IDS_SEPARATOR = ",";

    @Override
    @Transactional(readOnly = false)
    public void createSpuSpec(MallSpuSpec entity) {
        save(entity);
    }

    @Override
    @Transactional(readOnly = false)
    public void updateSpuSpec(MallSpuSpec entity) {
        update(entity);
    }

    @Override
    public List<MallSpuSpec> getSpuSpecs(String spuId) {
        MallSpuSpecQueryVO query = new MallSpuSpecQueryVO();
        query.setSpuId(spuId);
        return findList(query);
    }

    @Override
    @Transactional(readOnly = false)
    public void batchSaveSpuSpecs(String spuId, List<String> specIds) {
        deleteSpuSpecs(spuId);
        for (int i = 0; i < specIds.size(); i++) {
            MallSpuSpec spuSpec = new MallSpuSpec();
            spuSpec.setSpuId(spuId);
            spuSpec.setSpecId(specIds.get(i));
            spuSpec.setSortOrder(i);
            createSpuSpec(spuSpec);
        }
    }

    @Override
    @Transactional(readOnly = false)
    public void deleteSpuSpecs(String spuId) {
        List<MallSpuSpec> specs = getSpuSpecs(spuId);
        if (!specs.isEmpty()) {
            batchDelete(specs.stream().map(MallSpuSpec::getId).toList());
        }
    }
}
