package com.hc.business.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hc.business.dto.LiveDto;
import com.hc.business.mapper.ClassConfigMapper;
import com.hc.business.mapper.LiveClassMapper;
import com.hc.business.mapper.LiveMapper;
import com.hc.business.model.Live;
import com.hc.business.service.LiveService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 直播间表(Live)表服务实现类
 *
 * @author makejava
 * @since 2024-01-20 10:54:46
 */

@Service("liveService")
public class LiveServiceImpl implements LiveService {

    @Autowired
    private LiveClassMapper liveClassMapper;

    private final LiveMapper liveMapper;

    private final ClassConfigMapper classConfigMapper;

    public LiveServiceImpl(LiveMapper liveMapper, ClassConfigMapper classConfigMapper) {
        this.liveMapper = liveMapper;
        this.classConfigMapper = classConfigMapper;
    }

    /**
     * 通过ID查询单条数据
     *
     * @param liveId 主键
     * @return 实例对象
     */
    @Override
    public Live queryById(Integer liveId) {
        return this.liveMapper.selectByPrimaryKey(liveId);
    }

    /**
     * 新增数据
     *
     * @param live 实例对象
     * @return 实例对象
     */
    @Override
    public Live insert(Live live) {

        this.liveMapper.insert(live);
        return live;
    }

    /**
     * 修改数据
     *
     * @param live 实例对象
     * @return 实例对象
     */
    @Override
    public Live update(Live live) {
        this.liveMapper.updateByPrimaryKeySelective(live);
        return this.queryById(live.getLiveId());
    }

    /**
     * 通过主键删除数据
     *
     * @param liveId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer liveId) {
        return this.liveMapper.deleteByPrimaryKey(liveId) > 0;
    }

    /**
     * 分页查询多条数据
     *
     * @param page 页码
     * @param size 查询条数
     * @return 对象列表
     */
    @Override
    public PageInfo queryAllByLimit(int page, int size) {
        return PageHelper.startPage(page, size).doSelectPageInfo(this.liveMapper::selectAll);
    }

    @Override
    public List<LiveDto> queryListByUserIDAndLiveID(Integer userId, Integer liveId){
        List<LiveDto> list = this.liveMapper.queryListByUserIDAndLiveID(userId,liveId);
        List<LiveDto> dtoList = copyList(list);
        return dtoList;
    }

    private List<LiveDto> copyList(List<LiveDto> records) {
        List<LiveDto> list = new ArrayList<>();
        for (LiveDto record : records) {
            list.add(copy(record));
        }
        return list;
    }

    private LiveDto copy(LiveDto record) {
        LiveDto recordDto = new LiveDto();
        BeanUtils.copyProperties(record, recordDto);
        recordDto.setClassConfigModel(classConfigMapper.selectByPrimaryKey(record.getClassId()));
        return recordDto;
    }
}
