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

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jeesharp.business.modules.setting.convert.ClientAppVersionConvert;
import com.jeesharp.business.modules.setting.dto.ClientAppVersionSaveDTO;
import com.jeesharp.business.modules.setting.entity.CfgClientAppVersion;
import com.jeesharp.business.modules.setting.enums.ClientAppVersionStatusEnum;
import com.jeesharp.business.modules.setting.enums.ClientAppVersionTypeEnum;
import com.jeesharp.business.modules.setting.enums.ClientAppVersionUpdateStrategyEnum;
import com.jeesharp.business.modules.setting.service.ClientAppVersionService;
import com.jeesharp.business.modules.setting.vo.ClientAppVersionInfoVO;
import com.jeesharp.business.modules.setting.vo.ClientAppVersionListVO;
import com.jeesharp.business.modules.setting.vo.ClientAppVersionQueryVO;
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;

/**
 * C 端客户端版本发布后台管理应用服务：详情、分页、保存、删除。
 *
 * @author jeesharp
 * @since 2026-05-13
 */
@Service
@AllArgsConstructor
@Transactional(readOnly = true)
public class ClientAppVersionManageApplicationService {

    private final ClientAppVersionService clientAppVersionService;
    private final ObjectMapper objectMapper;

    public ClientAppVersionInfoVO get(String id) {
        CfgClientAppVersion entity = clientAppVersionService.get(id);
        if (entity == null) {
            return null;
        }
        ClientAppVersionInfoVO vo = ClientAppVersionConvert.INSTANCE.toInfoVO(entity);
        fillDisplayNames(vo);
        return vo;
    }

    public PageRespVO<ClientAppVersionListVO> findPage(Page<CfgClientAppVersion> page, ClientAppVersionQueryVO query) {
        Page<CfgClientAppVersion> result = clientAppVersionService.findPage(page, query);
        PageRespVO<ClientAppVersionListVO> pageResp = ClientAppVersionConvert.INSTANCE.toPageRespVO(result);
        if (pageResp.getRecords() != null) {
            pageResp.getRecords().forEach(this::fillDisplayNames);
        }
        return pageResp;
    }

    @Transactional(readOnly = false)
    public void save(ClientAppVersionSaveDTO dto) {
        validateJsonPayloads(dto.getPlatformsJson(), dto.getUpdateContentJson());
        validateEnumFields(dto.getVersionType(), dto.getUpdateType(), dto.getStatus());
        CfgClientAppVersion entity = ClientAppVersionConvert.INSTANCE.toEntity(dto);
        if (entity.getVersionType() == null) {
            entity.setVersionType(ClientAppVersionTypeEnum.STABLE.getValue());
        }
        if (entity.getUpdateType() == null) {
            entity.setUpdateType(ClientAppVersionUpdateStrategyEnum.OPTIONAL.getValue());
        }
        if (entity.getStatus() == null) {
            entity.setStatus(ClientAppVersionStatusEnum.DRAFT.getValue());
        }
        if (entity.getDelFlag() == null) {
            entity.setDelFlag("0");
        }
        if (StrUtil.isBlank(dto.getId())) {
            clientAppVersionService.createClientAppVersion(entity);
            return;
        }
        clientAppVersionService.updateClientAppVersion(entity);
    }

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

    private void validateJsonPayloads(String platformsJson, String updateContentJson) {
        try {
            JsonNode p = objectMapper.readTree(platformsJson);
            if (!p.isArray()) {
                throw new IllegalArgumentException("platformsJson 必须是 JSON 数组");
            }
        } catch (IllegalArgumentException e) {
            throw e;
        } catch (Exception e) {
            throw new IllegalArgumentException("platformsJson 不是合法 JSON");
        }
        try {
            JsonNode u = objectMapper.readTree(updateContentJson);
            if (!u.isObject()) {
                throw new IllegalArgumentException("updateContentJson 必须是 JSON 对象");
            }
        } catch (IllegalArgumentException e) {
            throw e;
        } catch (Exception e) {
            throw new IllegalArgumentException("updateContentJson 不是合法 JSON");
        }
    }

    private static void validateEnumFields(Integer versionType, Integer updateType, Integer status) {
        if (versionType != null && ClientAppVersionTypeEnum.fromValue(versionType) == null) {
            throw new IllegalArgumentException("版本类型不合法");
        }
        if (updateType != null && ClientAppVersionUpdateStrategyEnum.fromValue(updateType) == null) {
            throw new IllegalArgumentException("更新策略不合法");
        }
        if (status != null && ClientAppVersionStatusEnum.fromValue(status) == null) {
            throw new IllegalArgumentException("发布状态不合法");
        }
    }

    private void fillDisplayNames(ClientAppVersionInfoVO vo) {
        if (vo == null) {
            return;
        }
        vo.setStatusName(ClientAppVersionStatusEnum.getDescByValue(vo.getStatus()));
        vo.setVersionTypeName(ClientAppVersionTypeEnum.getDescByValue(vo.getVersionType()));
        vo.setUpdateTypeName(ClientAppVersionUpdateStrategyEnum.getDescByValue(vo.getUpdateType()));
    }

    private void fillDisplayNames(ClientAppVersionListVO vo) {
        if (vo == null) {
            return;
        }
        vo.setStatusName(ClientAppVersionStatusEnum.getDescByValue(vo.getStatus()));
        vo.setVersionTypeName(ClientAppVersionTypeEnum.getDescByValue(vo.getVersionType()));
        vo.setUpdateTypeName(ClientAppVersionUpdateStrategyEnum.getDescByValue(vo.getUpdateType()));
    }
}
