package co.yixiang.yshop.module.member.service.usertag;

import co.yixiang.yshop.module.member.service.usertagref.UserTagRefService;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;

import java.util.*;

import co.yixiang.yshop.module.member.controller.admin.usertag.vo.*;
import co.yixiang.yshop.module.member.dal.dataobject.usertag.UserTagDO;
import co.yixiang.yshop.framework.common.pojo.PageResult;

import co.yixiang.yshop.module.member.convert.usertag.UserTagConvert;
import co.yixiang.yshop.module.member.dal.mysql.usertag.UserTagMapper;

import static co.yixiang.yshop.framework.common.exception.util.ServiceExceptionUtil.exception;
import static co.yixiang.yshop.module.member.enums.ErrorCodeConstants.*;

/**
 * 会员标签 Service 实现类
 *
 * @author admin
 */
@Service
@Validated
public class UserTagServiceImpl implements UserTagService {

    @Resource
    private UserTagMapper userTagMapper;
    @Resource
    @Lazy
    private UserTagRefService userTagRefService;

    @Override
    public Long createUserTag(UserTagCreateReqVO createReqVO) {
        // 插入
        UserTagDO userTag = UserTagConvert.INSTANCE.convert(createReqVO);
        userTagMapper.insert(userTag);
        // 返回
        return userTag.getId();
    }

    @Override
    public void updateUserTag(UserTagUpdateReqVO updateReqVO) {
        // 校验存在
        validateUserTagExists(updateReqVO.getId());
        // 更新
        UserTagDO updateObj = UserTagConvert.INSTANCE.convert(updateReqVO);
        userTagMapper.updateById(updateObj);
    }

    @Override
    public void deleteUserTag(Long id) {
        // 校验存在
        validateUserTagExists(id);
        // 删除
        userTagMapper.deleteById(id);
    }

    private void validateUserTagExists(Long id) {
        if (userTagMapper.selectById(id) == null) {
            throw exception(USER_TAG_NOT_EXISTS);
        }
    }

    @Override
    public UserTagDO getUserTag(Long id) {
        return userTagMapper.selectById(id);
    }

    @Override
    public List<UserTagDO> getUserTagList(Collection<Long> ids) {
        return userTagMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<UserTagDO> getUserTagPage(UserTagPageReqVO pageReqVO) {
        PageResult<UserTagDO> result = userTagMapper.selectPage(pageReqVO);
        List<UserTagDO> list = result.getList();
        list.forEach(item -> {
            Long userCount = userTagRefService.selectCountByTagId(item.getId());
            item.setUserCount(userCount);
        });
        return result;
    }

    @Override
    public List<UserTagDO> getUserTagList(UserTagExportReqVO exportReqVO) {
        return userTagMapper.selectList(exportReqVO);
    }

    @Override
    public List<UserTagDO> getUserTagList(UserTagPageReqVO pageVO) {
        return userTagMapper.selectList2(pageVO);
    }

}
