package com.kxs.system.biz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kxs.common.core.exception.GlobalCustomerException;
import com.kxs.system.api.vo.kxsapp.school.SchoolListVO;
import com.kxs.system.biz.constant.enums.SysErrorTypeEnum;
import com.kxs.system.biz.mapper.KxsSchoolStudyMapper;
import com.kxs.system.api.model.KxsSchoolStudy;
import com.kxs.system.biz.service.KxsSchoolStudyService;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Optional;

/**
 * 商学院创客学堂(KxsSchoolStudy)表服务实现类
 *
 * @author 系统
 * @since 2023-12-15 12:16:31
 */
@Service("kxsSchoolStudyService")
public class KxsSchoolStudyServiceImpl extends ServiceImpl<KxsSchoolStudyMapper, KxsSchoolStudy> implements KxsSchoolStudyService {

    @Override
    public IPage<SchoolListVO> schoolList(Page<KxsSchoolStudy> page, Integer menuId) {
        //根据创建时间获取数据
        Page<KxsSchoolStudy> kxsSchoolStudyPage = page(page, Wrappers.<KxsSchoolStudy>lambdaQuery().eq(KxsSchoolStudy::getMenuId, menuId).orderByDesc(KxsSchoolStudy::getCreateTime));
        ArrayList<SchoolListVO> schoolListVOS = new ArrayList<>();
        //最新标记
        int isUpdate = 1;
        //根据取出顺序第一条数据既是最新数据
        for (KxsSchoolStudy record : kxsSchoolStudyPage.getRecords()) {
            SchoolListVO schoolListVO = new SchoolListVO();
            BeanUtil.copyProperties(record,schoolListVO);
            schoolListVO.setIsUpdate(isUpdate);
            schoolListVOS.add(schoolListVO);
            //取出第一条数据后修改标记
            if (isUpdate == 1){
                isUpdate = 0;
            }
        }
        //构造返回数据
        Page<SchoolListVO> schoolListVOPage = new Page<>();
        schoolListVOPage.setTotal(kxsSchoolStudyPage.getTotal());
        schoolListVOPage.setRecords(schoolListVOS);
        return schoolListVOPage;
    }

    @Override
    public Boolean incrRead(KxsSchoolStudy param) {

        KxsSchoolStudy schoolStudy = getById(param.getId());
        Optional.ofNullable(schoolStudy).orElseThrow(() -> new GlobalCustomerException(SysErrorTypeEnum.NOT_DATA.getDescription()));

        schoolStudy.setStudyPerson(schoolStudy.getStudyPerson() + 1);
        return updateById(schoolStudy);
    }
}

