package com.miaxis.collection.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.miaxis.collection.domain.CollectionInfo;
import com.miaxis.collection.mapper.CollectionInfoMapper;
import com.miaxis.collection.service.ICollectionInfoService;
import com.miaxis.collection.vo.CollectionCustomerVo;
import com.miaxis.common.core.domain.Response;
import com.miaxis.common.core.domain.entity.UserInfo;
import com.miaxis.common.exception.CustomException;
import com.miaxis.customer.mapper.CustomerInfoMapper;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;

/**
 * @Author wwl
 * @Date 2021/3/15
 * @Version 1.0
 */
@Service
@RequiredArgsConstructor
public class CollectionInfoServiceImpl extends ServiceImpl<CollectionInfoMapper, CollectionInfo> implements ICollectionInfoService {

    private final CollectionInfoMapper collectionInfoMapper;

    private final CustomerInfoMapper customerInfoMapper;


    /**
     * 查询用户收藏列表
     * @param userInfo
     * @return
     */
    @Override
    @SneakyThrows
    public List<CollectionCustomerVo> collectionList(UserInfo userInfo) {
        return customerInfoMapper.getCollectionList(userInfo.getId());
    }

    /**
     * applet
     * 收藏商家
     * @param userInfo 当前用户
     * @param id 商家id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response collectionBusiness(UserInfo userInfo, Long id) {
        try{
            List<CollectionInfo> infoList = collectionInfoMapper.selectByMap(new HashMap<String, Object>() {{
                put("user_id", userInfo.getId());
                put("customer_id", id);
            }});
            if (infoList.isEmpty()){
                //保存收藏表
                CollectionInfo collectionInfo = new CollectionInfo();
                collectionInfo.setUserId(userInfo.getId());
                collectionInfo.setCustomerId(id);
                collectionInfoMapper.insert(collectionInfo);
            }
            return Response.success();
        }catch (Exception e){
            throw new CustomException("系统异常");
        }
    }

    /**
     * 取消收藏
     * @param userId 当前用户id
     * @param ids 商家id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response removeCollectionByIds(Long userId, Long[] ids) {
        try{
            for (Long id : ids) {
                collectionInfoMapper.deleteByMap(new HashMap<String, Object>(){{
                    put("user_id",userId);
                    put("customer_id",id);
                }});
            }
            return Response.success();
        }catch (Exception e){
            throw new CustomException("系统异常");
        }

    }


}
