package com.gxwebsoft.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.shop.mapper.ViewHistoryMapper;
import com.gxwebsoft.shop.service.GoodsService;
import com.gxwebsoft.shop.service.ViewHistoryService;
import com.gxwebsoft.shop.entity.ViewHistory;
import com.gxwebsoft.shop.param.ViewHistoryParam;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 浏览历史Service实现
 *
 * @author 科技小王子
 * @since 2024-11-22 22:13:47
 */
@Service
public class ViewHistoryServiceImpl extends ServiceImpl<ViewHistoryMapper, ViewHistory> implements ViewHistoryService {
    @Resource
    private GoodsService goodsService;

    @Override
    public PageResult<ViewHistory> pageRel(ViewHistoryParam param) {
        PageParam<ViewHistory, ViewHistoryParam> page = new PageParam<>(param);
        page.setDefaultOrder("sort_number asc, create_time desc");
        List<ViewHistory> list = baseMapper.selectPageRel(page, param);
        return new PageResult<>(list, page.getTotal());
    }

    @Override
    public List<ViewHistory> listRel(ViewHistoryParam param) {
        List<ViewHistory> list = baseMapper.selectListRel(param);
        // 排序
        PageParam<ViewHistory, ViewHistoryParam> page = new PageParam<>();
        page.setDefaultOrder("sort_number asc, create_time desc");
        for (ViewHistory viewHistory : list) {
            if (viewHistory.getType().equals(0)) {
                viewHistory.setGoods(goodsService.getById(viewHistory.getPk()));
            }
        }
        return page.sortRecords(list);
    }

    @Override
    public ViewHistory getByIdRel(Integer id) {
        ViewHistoryParam param = new ViewHistoryParam();
        param.setId(id);
        return param.getOne(baseMapper.selectListRel(param));
    }

    @Override
    public ViewHistory check(Integer type, Integer pk, Integer userId) {
        return getOne(
                new LambdaQueryWrapper<ViewHistory>()
                        .eq(ViewHistory::getType, type)
                        .eq(ViewHistory::getPk, pk)
                        .eq(ViewHistory::getUserId, userId)
        );
    }

    @Override
    public ViewHistory check(Integer type, Integer pk, String openId) {
        return getOne(
                new LambdaQueryWrapper<ViewHistory>()
                        .eq(ViewHistory::getType, type)
                        .eq(ViewHistory::getPk, pk)
                        .eq(ViewHistory::getOpenId, openId)
        );
    }

}
