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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.mall.dto.MallSpuExtAttrSaveDTO;
import com.jeesharp.business.modules.mall.entity.MallSpuExtAttr;
import com.jeesharp.business.modules.mall.mapper.MallSpuExtAttrMapper;
import com.jeesharp.business.modules.mall.service.MallSpuExtAttrService;
import com.jeesharp.business.modules.mall.vo.MallSpuExtAttrQueryVO;
import com.jeesharp.framework.mybatis.core.service.CrudService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * SPU 扩展属性值领域服务实现。
 *
 * @author jeesharp
 * @since 2026-05-15
 */
@Service
@Transactional(readOnly = true)
public class MallSpuExtAttrServiceImpl extends CrudService<MallSpuExtAttrMapper, MallSpuExtAttr, MallSpuExtAttrQueryVO>
    implements MallSpuExtAttrService {

    @Override
    public List<MallSpuExtAttr> listBySpuId(String spuId) {
        if (StrUtil.isBlank(spuId)) {
            return List.of();
        }
        MallSpuExtAttrQueryVO q = new MallSpuExtAttrQueryVO();
        q.setSpuId(spuId);
        q.setPageNo(1L);
        q.setPageSize(500L);
        return findList(q);
    }

    @Override
    @Transactional(readOnly = false)
    public void deleteBySpuId(String spuId) {
        if (StrUtil.isBlank(spuId)) {
            return;
        }
        List<MallSpuExtAttr> list = listBySpuId(spuId);
        if (CollUtil.isEmpty(list)) {
            return;
        }
        batchDelete(list.stream().map(MallSpuExtAttr::getId).collect(Collectors.toList()));
    }

    @Override
    @Transactional(readOnly = false)
    public void replaceForSpu(String spuId, List<MallSpuExtAttrSaveDTO> rows) {
        deleteBySpuId(spuId);
        if (StrUtil.isBlank(spuId) || CollUtil.isEmpty(rows)) {
            return;
        }
        Map<String, MallSpuExtAttrSaveDTO> dedup = new LinkedHashMap<>();
        for (MallSpuExtAttrSaveDTO d : rows) {
            if (d == null || StrUtil.isBlank(d.getAttrKey())) {
                continue;
            }
            String val = d.getAttrValue() == null ? "" : d.getAttrValue().trim();
            if (StrUtil.isBlank(val)) {
                continue;
            }
            dedup.put(d.getAttrKey().trim(), d);
        }
        for (MallSpuExtAttrSaveDTO d : dedup.values()) {
            MallSpuExtAttr e = new MallSpuExtAttr();
            e.setSpuId(spuId);
            e.setAttrKey(d.getAttrKey().trim());
            String tv = d.getAttrValue() == null ? "" : d.getAttrValue().trim();
            e.setAttrValue(tv);
            save(e);
        }
    }
}
