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

import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.setting.application.support.HomeQuickGridIntroLayoutSupport;
import com.jeesharp.business.modules.setting.convert.HomeGridIntroConvert;
import com.jeesharp.business.modules.setting.dto.HomeGridIntroSaveDTO;
import com.jeesharp.business.modules.setting.entity.CmsHomeGridIntro;
import com.jeesharp.business.modules.setting.entity.CmsHomeQuickGrid;
import com.jeesharp.business.modules.setting.enums.HomeGridIntroLayoutEnum;
import com.jeesharp.business.modules.setting.enums.HomeQuickGridIntroListLayoutEnum;
import com.jeesharp.business.modules.setting.enums.SettingPublishStatusEnum;
import com.jeesharp.business.modules.setting.service.HomeGridIntroService;
import com.jeesharp.business.modules.setting.service.HomeQuickGridService;
import com.jeesharp.business.modules.setting.vo.HomeGridIntroListVO;
import com.jeesharp.business.modules.setting.vo.HomeGridIntroMobileDetailVO;
import com.jeesharp.business.modules.setting.vo.HomeGridIntroMobileItemVO;
import com.jeesharp.business.modules.setting.vo.HomeGridIntroMobilePageVO;
import com.jeesharp.business.modules.setting.vo.HomeGridIntroQueryVO;
import com.jeesharp.business.modules.setting.vo.HomeGridIntroVO;
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.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * 首页宫格介绍文章应用服务：后台 CRUD 与小程序分页列表、详情（已发布）。
 *
 * @author jeesharp
 * @since 2026-05-15
 */
@Service
@AllArgsConstructor
@Transactional(readOnly = true)
public class HomeGridIntroApplicationService {

    private static final DateTimeFormatter PUBLISH_FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    private final HomeGridIntroService homeGridIntroService;
    private final HomeQuickGridService homeQuickGridService;

    public HomeGridIntroVO get(String id) {
        CmsHomeGridIntro entity = homeGridIntroService.get(id);
        if (entity == null) {
            return null;
        }
        HomeGridIntroVO vo = HomeGridIntroConvert.INSTANCE.toInfoVO(entity);
        fillStatusName(vo);
        fillLayoutName(vo);
        return vo;
    }

    public PageRespVO<HomeGridIntroListVO> findPage(Page<CmsHomeGridIntro> page, HomeGridIntroQueryVO query) {
        Page<CmsHomeGridIntro> result = homeGridIntroService.findPage(page, query);
        PageRespVO<HomeGridIntroListVO> pageResp = HomeGridIntroConvert.INSTANCE.toPageRespVO(result);
        if (pageResp.getRecords() != null) {
            pageResp.getRecords().forEach(row -> {
                fillStatusName(row);
                fillLayoutName(row);
            });
        }
        return pageResp;
    }

    @Transactional(readOnly = false)
    public void save(HomeGridIntroSaveDTO dto) {
        String qid = StrUtil.trimToEmpty(dto.getQuickGridId());
        if (StrUtil.isBlank(qid)) {
            throw new IllegalArgumentException("所属宫格不能为空");
        }
        CmsHomeQuickGrid grid = homeQuickGridService.get(qid);
        if (grid == null) {
            throw new IllegalArgumentException("所属宫格不存在或已删除");
        }
        CmsHomeGridIntro entity = HomeGridIntroConvert.INSTANCE.toEntity(dto);
        entity.setQuickGridId(qid);
        String title = StrUtil.trimToEmpty(entity.getTitle());
        if (StrUtil.isBlank(title)) {
            throw new IllegalArgumentException("标题不能为空");
        }
        entity.setTitle(title);
        if (entity.getStatus() == null) {
            entity.setStatus(SettingPublishStatusEnum.DRAFT.getValue());
        } else if (SettingPublishStatusEnum.fromValue(entity.getStatus()) == null) {
            throw new IllegalArgumentException("状态取值不合法");
        }
        if (entity.getSortNo() == null) {
            entity.setSortNo(0);
        }
        if (entity.getLayout() == null) {
            entity.setLayout(HomeGridIntroLayoutEnum.STANDARD.getValue());
        } else if (HomeGridIntroLayoutEnum.fromValue(entity.getLayout()) == null) {
            throw new IllegalArgumentException("布局取值不合法");
        }
        entity.setImagesJson(normalizeImagesJson(dto.getImagesJson()));
        entity.setTagsJson(HomeQuickGridIntroLayoutSupport.normalizeTagsJson(dto.getTagsJson()));
        entity.setCategory(StrUtil.trimToNull(dto.getCategory()));
        if (StrUtil.isBlank(dto.getId())) {
            homeGridIntroService.save(entity);
            return;
        }
        homeGridIntroService.update(entity);
    }

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

    /**
     * 小程序分页：指定宫格下已发布文章。
     */
    public HomeGridIntroMobilePageVO findPublishedPage(String quickGridId, long pageNo, long pageSize, String category) {
        String qid = StrUtil.trimToEmpty(quickGridId);
        HomeGridIntroMobilePageVO out = new HomeGridIntroMobilePageVO();
        out.setPage(pageNo);
        out.setPageSize(pageSize);
        if (StrUtil.isBlank(qid)) {
            out.setTotal(0L);
            out.setList(new ArrayList<>());
            out.setListLayout(HomeQuickGridIntroListLayoutEnum.CARD.getValue());
            out.setListLayoutName(HomeQuickGridIntroListLayoutEnum.CARD.getDesc());
            return out;
        }
        CmsHomeQuickGrid grid = homeQuickGridService.get(qid);
        int layoutVal = HomeQuickGridIntroLayoutSupport.resolveListLayout(grid);
        out.setListLayout(layoutVal);
        out.setListLayoutName(HomeQuickGridIntroListLayoutEnum.getDescByValue(layoutVal));
        if (grid != null) {
            out.setBanners(HomeQuickGridIntroLayoutSupport.parseBanners(grid.getIntroBannerJson()));
        }
        List<CmsHomeGridIntro> allPublished = listAllPublished(qid);
        out.setTabLabels(HomeQuickGridIntroLayoutSupport.buildTabLabels(grid, allPublished));

        HomeGridIntroQueryVO q = new HomeGridIntroQueryVO();
        q.setPageNo(pageNo);
        q.setPageSize(pageSize);
        q.setQuickGridId(qid);
        q.setStatus(SettingPublishStatusEnum.PUBLISHED.getValue());
        String cat = StrUtil.trimToNull(category);
        if (cat != null && !"全部".equals(cat)) {
            q.setCategory(cat);
        }
        Page<CmsHomeGridIntro> page = new Page<>(q);
        Page<CmsHomeGridIntro> result = homeGridIntroService.findPage(page, q);
        out.setTotal(result.getTotal());
        List<HomeGridIntroMobileItemVO> list = new ArrayList<>();
        if (result.getRecords() != null) {
            for (CmsHomeGridIntro e : result.getRecords()) {
                list.add(toMobileItem(e));
            }
        }
        out.setList(list);
        return out;
    }

    private List<CmsHomeGridIntro> listAllPublished(String quickGridId) {
        HomeGridIntroQueryVO q = new HomeGridIntroQueryVO();
        q.setPageNo(1L);
        q.setPageSize(500L);
        q.setQuickGridId(quickGridId);
        q.setStatus(SettingPublishStatusEnum.PUBLISHED.getValue());
        Page<CmsHomeGridIntro> page = new Page<>(q);
        Page<CmsHomeGridIntro> result = homeGridIntroService.findPage(page, q);
        return result.getRecords() == null ? new ArrayList<>() : result.getRecords();
    }

    /**
     * 小程序详情：已发布；若传入 quickGridId 则校验归属。
     */
    public HomeGridIntroMobileDetailVO getMobileDetail(String id, String quickGridId) {
        CmsHomeGridIntro entity = homeGridIntroService.get(id);
        if (entity == null || !SettingPublishStatusEnum.PUBLISHED.getValue().equals(entity.getStatus())) {
            return null;
        }
        String qid = StrUtil.trimToNull(quickGridId);
        if (qid != null && !qid.equals(entity.getQuickGridId())) {
            return null;
        }
        return toMobileDetail(entity);
    }

    private HomeGridIntroMobileItemVO toMobileItem(CmsHomeGridIntro entity) {
        HomeGridIntroMobileItemVO vo = new HomeGridIntroMobileItemVO();
        vo.setId(entity.getId());
        vo.setTitle(entity.getTitle());
        vo.setSummary(entity.getSummary());
        vo.setCategory(entity.getCategory());
        vo.setTags(HomeQuickGridIntroLayoutSupport.parseTags(entity.getTagsJson()));
        vo.setCoverImage(entity.getCoverImage());
        vo.setPublishDate(entity.getPublishDate() == null ? null : PUBLISH_FMT.format(entity.getPublishDate()));
        return vo;
    }

    private HomeGridIntroMobileDetailVO toMobileDetail(CmsHomeGridIntro entity) {
        HomeGridIntroMobileDetailVO vo = new HomeGridIntroMobileDetailVO();
        vo.setId(entity.getId());
        vo.setQuickGridId(entity.getQuickGridId());
        vo.setTitle(entity.getTitle());
        vo.setSummary(entity.getSummary());
        vo.setCoverImage(entity.getCoverImage());
        vo.setImagesJson(entity.getImagesJson());
        vo.setContent(entity.getContent());
        vo.setLayout(entity.getLayout() == null
                ? HomeGridIntroLayoutEnum.STANDARD.getValue()
                : entity.getLayout());
        vo.setPublishDate(entity.getPublishDate() == null ? null : PUBLISH_FMT.format(entity.getPublishDate()));
        return vo;
    }

    private void fillStatusName(HomeGridIntroVO vo) {
        if (vo == null) {
            return;
        }
        vo.setStatusName(SettingPublishStatusEnum.getDescByValue(vo.getStatus()));
    }

    private void fillStatusName(HomeGridIntroListVO vo) {
        if (vo == null) {
            return;
        }
        vo.setStatusName(SettingPublishStatusEnum.getDescByValue(vo.getStatus()));
    }

    private void fillLayoutName(HomeGridIntroVO vo) {
        if (vo == null) {
            return;
        }
        if (vo.getLayout() == null) {
            vo.setLayout(HomeGridIntroLayoutEnum.STANDARD.getValue());
        }
        vo.setLayoutName(HomeGridIntroLayoutEnum.getDescByValue(vo.getLayout()));
    }

    private void fillLayoutName(HomeGridIntroListVO vo) {
        if (vo == null) {
            return;
        }
        if (vo.getLayout() == null) {
            vo.setLayout(HomeGridIntroLayoutEnum.STANDARD.getValue());
        }
        vo.setLayoutName(HomeGridIntroLayoutEnum.getDescByValue(vo.getLayout()));
    }

    /**
     * 图片集 JSON 规范化：空值转 {@code []}，非数组则抛错。
     */
    private String normalizeImagesJson(String raw) {
        String trimmed = StrUtil.trimToEmpty(raw);
        if (StrUtil.isBlank(trimmed)) {
            return "[]";
        }
        if (!trimmed.startsWith("[")) {
            throw new IllegalArgumentException("图片集须为 JSON 数组");
        }
        return trimmed;
    }
}
