package com.kym.service.miniapp.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kym.entity.enplus.EnStationStatusInfo;
import com.kym.entity.miniapp.Collect;
import com.kym.mapper.miniapp.CollectMapper;
import com.kym.service.admin.StationService;
import com.kym.service.miniapp.CollectService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 收藏表 服务实现类
 * </p>
 *
 * @author skyline
 * @since 2023-07-31
 */
@Service
@DS("db-miniapp")
public class CollectServiceImpl extends ServiceImpl<CollectMapper, Collect> implements CollectService {

    private final StationService stationService;

    public CollectServiceImpl(StationService stationService) {
        this.stationService = stationService;
    }

    /**
     * 添加/取消收藏
     *
     * @param stationId
     * @param status
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateCollect(String stationId, Integer status) {
        var userId = StpUtil.getLoginIdAsLong();

        switch (status) {
            case 1 -> // 收藏
            {
                var collect = new Collect();
                collect.setUserId(userId);
                collect.setStationId(stationId);
                collect.setStatus(status);
                var exist = lambdaQuery().eq(Collect::getUserId, userId).eq(Collect::getStationId, stationId).exists();
                if (!exist) {
                    save(collect);
                } else {
                    lambdaUpdate().set(Collect::getStatus, status).eq(Collect::getUserId, userId).eq(Collect::getStationId, stationId).update();
                }
            }
            case 0 -> // 取消收藏
                    lambdaUpdate().set(Collect::getStatus, status).eq(Collect::getUserId, userId).eq(Collect::getStationId, stationId).update();
        }

    }

    /**
     * 收藏列表
     * 获取EN+对应站点数据
     *
     * @return
     */
    @Override
    public List<EnStationStatusInfo> getCollectList() {
        var userid = StpUtil.getLoginIdAsLong();
        var collectList = lambdaQuery().eq(Collect::getUserId, userid).list().stream().map(c -> String.valueOf(c.getStationId())).toArray(String[]::new);
        if (collectList.length == 0) {
            return stationService.stationStatus(collectList);
        } else {
            return null;
        }

    }

    /**
     * 获取收藏列表，前端匹配站点详情数据
     *
     * @return
     */
    @Override
    public List<Collect> listCollect() {
        var userid = StpUtil.getLoginIdAsLong();
        return lambdaQuery().eq(Collect::getUserId, userid).list();
    }

}
