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

import com.jeesharp.business.modules.common.enums.DisabledEnabledEnum;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.mall.entity.MallCategory;
import com.jeesharp.business.modules.mall.entity.MallCategorySpec;
import com.jeesharp.business.modules.mall.entity.MallSpec;

import com.jeesharp.business.modules.mall.mapper.MallCategorySpecMapper;
import com.jeesharp.business.modules.mall.mapper.MallSpecMapper;
import com.jeesharp.business.modules.mall.service.MallCategoryService;
import com.jeesharp.business.modules.mall.service.MallCategorySpecService;
import com.jeesharp.business.modules.common.constants.PlatformTenantConstants;
import com.jeesharp.business.modules.mall.vo.MallCategorySpecQueryVO;
import com.jeesharp.business.modules.mall.vo.MallSpecOptionVO;
import com.jeesharp.framework.exception.BizErrorException;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;

/**
 * 类目规格白名单领域服务实现。
 *
 * @author jeesharp
 * @since 2026-05-15
 */
@Service
@AllArgsConstructor
@Transactional(readOnly = true)
public class MallCategorySpecServiceImpl implements MallCategorySpecService {

    private final MallCategorySpecMapper mallCategorySpecMapper;
    private final MallCategoryService mallCategoryService;
    private final MallSpecMapper mallSpecMapper;

    /**
     * 按类目查询已纳入白名单的规格选项（联查 {@code mall_spec}）。
     * <p>不校验是否为末级类目：父级类目上通常无白名单行，返回空列表即可；发布模板编辑页可能以「仅绑定父级」的类目 id 筛选，
     * 若此处强制末级会与 {@link #replaceSpecsForCategory} 的约束不一致并导致接口报错。</p>
     * <p>写入白名单仍须末级，见 {@link #replaceSpecsForCategory}。</p>
     */
    @Override
    public List<MallSpecOptionVO> listSpecOptionsByCategoryId(String categoryId) {
        if (StrUtil.isBlank(categoryId)) {
            return List.of();
        }
        String cid = categoryId.trim();
        return mallCategorySpecMapper.selectSpecOptionsByCategoryId(
            PlatformTenantConstants.PLATFORM_TENANT_CODE,
            cid);
    }

    @Override
    public List<MallSpecOptionVO> listSpecOptionsByTemplateId(String templateId) {
        if (StrUtil.isBlank(templateId)) {
            return List.of();
        }
        return mallCategorySpecMapper.selectSpecOptionsByTemplateId(
            PlatformTenantConstants.PLATFORM_TENANT_CODE,
            templateId.trim());
    }

    @Override
    @Transactional(readOnly = false)
    public void replaceSpecsForCategory(String categoryId, List<String> specIds) {
        if (StrUtil.isBlank(categoryId)) {
            throw new BizErrorException("类目ID不能为空");
        }
        String cid = categoryId.trim();
        MallCategory cat = mallCategoryService.get(cid);
        if (cat == null) {
            throw new BizErrorException("类目不存在或已删除");
        }
        ensureLeafCategoryForSpecConfig(cid);
        List<String> ordered = dedupePreserveOrder(specIds);
        MallCategorySpecQueryVO q = new MallCategorySpecQueryVO();
        q.setCategoryId(cid);
        q.setPageNo(1L);
        q.setPageSize(5000L);
        List<MallCategorySpec> existing = mallCategorySpecMapper.findList(q);
        if (CollUtil.isNotEmpty(existing)) {
            List<String> oldIds = existing.stream().map(MallCategorySpec::getId).distinct().toList();
            if (!oldIds.isEmpty()) {
                mallCategorySpecMapper.batchDelete(oldIds.toArray(new String[0]));
            }
        }
        int i = 0;
        for (String specId : ordered) {
            MallSpec spec = mallSpecMapper.get(specId);
            if (spec == null) {
                throw new BizErrorException("规格不存在: " + specId);
            }
            if (!DisabledEnabledEnum.ENABLED.getValue().equals(spec.getStatus())) {
                throw new BizErrorException("规格未启用: " + specId);
            }
            MallCategorySpec row = new MallCategorySpec();
            row.setCategoryId(cid);
            row.setSpecId(specId);
            row.setSortOrder(i++);
            row.setTenantId(cat.getTenantId());
            row.setTenantCode(cat.getTenantCode());
            mallCategorySpecMapper.insert(row);
        }
    }

    private static List<String> dedupePreserveOrder(List<String> specIds) {
        if (CollUtil.isEmpty(specIds)) {
            return List.of();
        }
        LinkedHashSet<String> set = new LinkedHashSet<>();
        for (String x : specIds) {
            if (StrUtil.isNotBlank(x)) {
                set.add(x.trim());
            }
        }
        return new ArrayList<>(set);
    }

    /**
     * 可用规格仅允许配置在末级类目（无子类目）上。
     */
    private void ensureLeafCategoryForSpecConfig(String categoryId) {
        if (mallCategoryService.hasChildCategory(categoryId)) {
            throw new BizErrorException("仅末级类目可配置可用规格，请先维护子类目或选择叶子类目");
        }
    }
}
