package com.gxwebsoft.house.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.gxwebsoft.house.entity.HouseInfo;
import com.gxwebsoft.house.mapper.HouseViewsLogMapper;
import com.gxwebsoft.house.service.HouseViewsLogService;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.gxwebsoft.house.entity.HouseViewsLog;
import com.gxwebsoft.house.param.HouseViewsLogParam;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 看房记录表Service实现
 *
 * @author 科技小王子
 * @since 2025-03-05 13:47:15
 */
@Service
public class HouseViewsLogServiceImpl extends MPJBaseServiceImpl<HouseViewsLogMapper, HouseViewsLog> implements HouseViewsLogService {

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

    @Override
    public List<HouseViewsLog> listRel(HouseViewsLogParam param) {
        List<HouseViewsLog> list = baseMapper.selectListRel(param);
        // 排序
        PageParam<HouseViewsLog, HouseViewsLogParam> page = new PageParam<>();
        page.setDefaultOrder("sort_number asc, create_time desc");
        return page.sortRecords(list);
    }

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

    @Override
    public void add(HouseInfo houseInfo, Integer loginUserId) {
      LambdaQueryWrapper<HouseViewsLog> wrapper = Wrappers.lambdaQuery(HouseViewsLog.class).eq(HouseViewsLog::getUserId, loginUserId).eq(HouseViewsLog::getHouseId, houseInfo.getHouseId());
      HouseViewsLog viewsLog = baseMapper.selectOne(wrapper);
      if(viewsLog == null){
        viewsLog = new HouseViewsLog();
        viewsLog.setUserId(loginUserId);
        viewsLog.setHouseId(houseInfo.getHouseId());
        viewsLog.setHouseUserId(houseInfo.getUserId());
      }
      viewsLog.setUpdateTime(LocalDateTime.now());
      saveOrUpdate(viewsLog);
    }

}
