package com.jeesharp.business.modules.setting.application;

import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.setting.convert.SiteIconConvert;
import com.jeesharp.business.modules.setting.dto.SiteIconSaveDTO;
import com.jeesharp.business.modules.setting.entity.CmsSiteIcon;
import com.jeesharp.business.modules.setting.enums.SiteIconCategoryEnum;
import com.jeesharp.business.modules.setting.enums.SiteIconStatusEnum;
import com.jeesharp.business.modules.setting.service.SiteIconService;
import com.jeesharp.business.modules.setting.vo.MiniHomeSiteIconItemVO;
import com.jeesharp.business.modules.setting.vo.SiteIconListVO;
import com.jeesharp.business.modules.setting.vo.SiteIconQueryVO;
import com.jeesharp.business.modules.setting.vo.SiteIconVO;
import com.jeesharp.framework.pojo.Page;
import com.jeesharp.framework.pojo.query.PageRespVO;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 站点图标应用服务：后台 CRUD、编号唯一校验，以及向小程序壳层提供首页分类图标列表。
 *
 * @author jeesharp
 * @since 2026-05-15
 */
@Service
@AllArgsConstructor
@Transactional(readOnly = true)
public class SiteIconApplicationService {

    private final SiteIconService siteIconService;

    public SiteIconVO get(String id) {
        CmsSiteIcon entity = siteIconService.get(id);
        if (entity == null) {
            return null;
        }
        SiteIconVO vo = SiteIconConvert.INSTANCE.toInfoVO(entity);
        fillNames(vo);
        return vo;
    }

    public PageRespVO<SiteIconListVO> findPage(Page<CmsSiteIcon> page, SiteIconQueryVO query) {
        Page<CmsSiteIcon> result = siteIconService.findPage(page, query);
        PageRespVO<SiteIconListVO> pageResp = SiteIconConvert.INSTANCE.toPageRespVO(result);
        if (pageResp.getRecords() != null) {
            pageResp.getRecords().forEach(this::fillNames);
        }
        return pageResp;
    }

    @Transactional(readOnly = false)
    public void save(SiteIconSaveDTO dto) {
        CmsSiteIcon entity = SiteIconConvert.INSTANCE.toEntity(dto);
        String code = StrUtil.trimToEmpty(entity.getIconCode());
        if (StrUtil.isBlank(code)) {
            throw new IllegalArgumentException("图标编号不能为空");
        }
        entity.setIconCode(code);
        String cat = StrUtil.trimToEmpty(entity.getCategory());
        if (StrUtil.isBlank(cat)) {
            throw new IllegalArgumentException("分类不能为空");
        }
        if (SiteIconCategoryEnum.fromCode(cat) == null) {
            throw new IllegalArgumentException("分类取值不合法，可选：HOME、COMMON、MALL");
        }
        entity.setCategory(cat.toUpperCase());
        String url = StrUtil.trimToEmpty(entity.getIconUrl());
        if (StrUtil.isBlank(url)) {
            throw new IllegalArgumentException("图标地址不能为空");
        }
        entity.setIconUrl(url);
        entity.setDisplayName(StrUtil.trimToNull(entity.getDisplayName()));
        if (entity.getStatus() == null) {
            entity.setStatus(SiteIconStatusEnum.ENABLED.getValue());
        } else if (SiteIconStatusEnum.fromValue(entity.getStatus()) == null) {
            throw new IllegalArgumentException("状态取值不合法");
        }
        if (entity.getSortOrder() == null) {
            entity.setSortOrder(0);
        }
        String excludeId = StrUtil.isBlank(dto.getId()) ? null : dto.getId().trim();
        if (siteIconService.countByIconCodeExcludeId(entity.getIconCode(), excludeId) > 0L) {
            throw new IllegalArgumentException("图标编号已存在");
        }
        if (StrUtil.isBlank(dto.getId())) {
            siteIconService.save(entity);
            return;
        }
        siteIconService.update(entity);
    }

    @Transactional(readOnly = false)
    public void delete(String ids) {
        siteIconService.batchDelete(StrUtil.splitTrim(ids, ','));
    }

    /**
     * 小程序壳层：{@link SiteIconCategoryEnum#HOME} 启用项，并合并 {@link SiteIconCategoryEnum#COMMON} 下
     * 编号前缀为 {@code travel_entrance_} 的旅游入口素材（与 cms_site_icon 种子一致），供端上按 iconCode 覆盖宫格与营销条背景。
     *
     * @return 列表（可能为空）
     */
    public List<MiniHomeSiteIconItemVO> listShellHomeItems() {
        List<MiniHomeSiteIconItemVO> out = new ArrayList<>();
        out.addAll(toShellSiteIconItems(siteIconService.listEnabledByCategory(SiteIconCategoryEnum.HOME.getCode())));
        out.addAll(toShellSiteIconItems(
            siteIconService.listEnabledByCategoryAndIconCodePrefix(
                SiteIconCategoryEnum.COMMON.getCode(),
                "travel_entrance_")));
        return out;
    }

    private List<MiniHomeSiteIconItemVO> toShellSiteIconItems(List<CmsSiteIcon> rows) {
        if (rows == null || rows.isEmpty()) {
            return List.of();
        }
        List<MiniHomeSiteIconItemVO> out = new ArrayList<>();
        for (CmsSiteIcon e : rows) {
            String u = StrUtil.trimToEmpty(e.getIconUrl());
            if (u.isEmpty()) {
                continue;
            }
            MiniHomeSiteIconItemVO vo = new MiniHomeSiteIconItemVO();
            vo.setIconCode(StrUtil.trimToEmpty(e.getIconCode()));
            vo.setIconUrl(u);
            if (StrUtil.isNotBlank(vo.getIconCode())) {
                out.add(vo);
            }
        }
        return out;
    }

    private void fillNames(SiteIconVO vo) {
        if (vo == null) {
            return;
        }
        vo.setStatusName(SiteIconStatusEnum.getDescByValue(vo.getStatus()));
        vo.setCategoryName(SiteIconCategoryEnum.getDescByCode(vo.getCategory()));
    }

    private void fillNames(SiteIconListVO vo) {
        if (vo == null) {
            return;
        }
        vo.setStatusName(SiteIconStatusEnum.getDescByValue(vo.getStatus()));
        vo.setCategoryName(SiteIconCategoryEnum.getDescByCode(vo.getCategory()));
    }
}
