package com.nanri.aiimage.modules.shopkey.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.security.ShopCredentialCryptoService;
import com.nanri.aiimage.modules.shopkey.mapper.ShopManageMapper;
import com.nanri.aiimage.modules.shopkey.model.dto.ShopManageCreateRequest;
import com.nanri.aiimage.modules.shopkey.model.dto.ShopManageUpdateRequest;
import com.nanri.aiimage.modules.shopkey.model.entity.ShopManageEntity;
import com.nanri.aiimage.modules.shopkey.model.entity.ShopManageGroupEntity;
import com.nanri.aiimage.modules.shopkey.model.vo.ShopManageItemVo;
import com.nanri.aiimage.modules.shopkey.model.vo.ShopManagePageVo;
import com.nanri.aiimage.modules.shopkey.model.vo.ShopManageCredentialVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
@RequiredArgsConstructor
public class ShopManageService {

    private final ShopManageMapper shopManageMapper;
    private final ShopManageGroupService shopManageGroupService;
    private final ShopCredentialCryptoService shopCredentialCryptoService;

    public ShopManagePageVo page(long page, long pageSize) {
        long safePage = Math.max(page, 1);
        long safePageSize = Math.min(Math.max(pageSize, 1), 100);
        LambdaQueryWrapper<ShopManageEntity> query = new LambdaQueryWrapper<ShopManageEntity>()
                .orderByDesc(ShopManageEntity::getId);
        Long total = shopManageMapper.selectCount(query);
        List<ShopManageEntity> rows = shopManageMapper
                .selectList(query.last("LIMIT " + ((safePage - 1) * safePageSize) + ", " + safePageSize));

Map<Long, String> groupNameById = buildGroupNameMap(rows.stream()
                .map(ShopManageEntity::getGroupId)
                .filter(id -> id != null && id > 0)
                .distinct()
                .toList());

        List<ShopManageItemVo> items = rows.stream()
                .map(entity -> toItemVo(entity, groupNameById.get(entity.getGroupId())))
                .toList();
        ShopManagePageVo vo = new ShopManagePageVo();
        vo.setItems(items);
        vo.setTotal(total);
        vo.setPage(safePage);
        vo.setPageSize(safePageSize);
        return vo;
    }

    @Transactional
    public ShopManageItemVo create(ShopManageCreateRequest request) {
        ShopManageGroupEntity group = shopManageGroupService.getById(request.getGroupId());
        String shopName = normalizeRequired(request.getShopName(), "店铺名不能为空");
        ensureShopNameUnique(shopName, null);

        ShopManageEntity entity = new ShopManageEntity();
        entity.setGroupId(group.getId());
        entity.setGroupName(group.getGroupName());
        entity.setShopName(shopName);
        entity.setAccount(normalizeRequired(request.getAccount(), "账号不能为空"));
        entity.setPassword(shopCredentialCryptoService.encrypt(normalizeRequired(request.getPassword(), "密码不能为空")));
        shopManageMapper.insert(entity);
        ShopManageEntity saved = getById(entity.getId());
        return toItemVo(saved, group.getGroupName());
    }

    @Transactional
    public ShopManageItemVo update(Long id, ShopManageUpdateRequest request) {
        ShopManageEntity entity = getById(id);
        ShopManageGroupEntity group = shopManageGroupService.getById(request.getGroupId());
        String shopName = normalizeRequired(request.getShopName(), "店铺名不能为空");
        ensureShopNameUnique(shopName, id);

        entity.setGroupId(group.getId());
        entity.setGroupName(group.getGroupName());
        entity.setShopName(shopName);
        entity.setAccount(normalizeRequired(request.getAccount(), "账号不能为空"));
        entity.setPassword(shopCredentialCryptoService.encrypt(normalizeRequired(request.getPassword(), "密码不能为空")));
        shopManageMapper.updateById(entity);
        ShopManageEntity updated = getById(id);
        return toItemVo(updated, group.getGroupName());
    }

    @Transactional
    public void delete(Long id) {
        ShopManageEntity entity = getById(id);
        shopManageMapper.deleteById(entity.getId());
    }

    public ShopManageCredentialVo getCredentialByShopName(String shopName) {
        String normalizedShopName = normalizeRequired(shopName, "店铺名不能为空");
        ShopManageEntity entity = shopManageMapper.selectOne(new LambdaQueryWrapper<ShopManageEntity>()
                .eq(ShopManageEntity::getShopName, normalizedShopName)
                .last("limit 1"));
        if (entity == null) {
            throw new BusinessException("店铺不存在");
        }
        ShopManageCredentialVo vo = new ShopManageCredentialVo();
        vo.setId(entity.getId());
        vo.setGroupId(entity.getGroupId());
        vo.setShopName(entity.getShopName());
        vo.setAccount(entity.getAccount());
        vo.setPassword(shopCredentialCryptoService.decrypt(entity.getPassword()));
        try {
            ShopManageGroupEntity group = shopManageGroupService.getById(entity.getGroupId());
            vo.setGroupName(group.getGroupName());
        } catch (Exception ignored) {
            vo.setGroupName("");
        }
        return vo;
    }

    private ShopManageEntity getById(Long id) {
        ShopManageEntity entity = shopManageMapper.selectById(id);
        if (entity == null) {
            throw new BusinessException("店铺不存在");
        }
        return entity;
    }

    private String normalizeRequired(String value, String message) {
        String normalized = value == null ? "" : value.trim();
        if (normalized.isEmpty()) {
            throw new BusinessException(message);
        }
        return normalized;
    }

    private void ensureShopNameUnique(String shopName, Long excludeId) {
        LambdaQueryWrapper<ShopManageEntity> query = new LambdaQueryWrapper<ShopManageEntity>()
                .eq(ShopManageEntity::getShopName, shopName);
        if (excludeId != null) {
            query.ne(ShopManageEntity::getId, excludeId);
        }
        Long count = shopManageMapper.selectCount(query);
        if (count != null && count > 0) {
            throw new BusinessException("店铺名已存在");
        }
    }

    private Map<Long, String> buildGroupNameMap(List<Long> groupIds) {
        if (groupIds == null || groupIds.isEmpty()) {
            return Map.of();
        }
        LinkedHashMap<Long, String> map = new LinkedHashMap<>();
        for (Long groupId : groupIds) {
            try {
                ShopManageGroupEntity g = shopManageGroupService.getById(groupId);
                map.put(groupId, g.getGroupName());
            } catch (Exception ignored) {
                map.put(groupId, "");
            }
        }
        return map;
    }

    private ShopManageItemVo toItemVo(ShopManageEntity entity, String groupName) {
        ShopManageItemVo vo = new ShopManageItemVo();
        vo.setId(entity.getId());
        vo.setGroupId(entity.getGroupId());
        vo.setGroupName(groupName == null ? "" : groupName);
        vo.setShopName(entity.getShopName());
        vo.setAccount(entity.getAccount());
        String masked = entity.getPassword() == null || entity.getPassword().isBlank() ? "" : "******";
        // 兼容旧前端字段：password 继续返回脱敏值
        vo.setPassword(masked);
        vo.setPasswordMasked(masked);
        vo.setCreatedAt(entity.getCreatedAt());
        vo.setUpdatedAt(entity.getUpdatedAt());
        return vo;
    }
}
