package com.yonge.cooleshow.biz.dal.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yonge.cooleshow.biz.dal.dao.MusicSheetAuthRecordDao;
import com.yonge.cooleshow.biz.dal.dto.req.TeacherMusicSheetAuditReq;
import com.yonge.cooleshow.biz.dal.entity.MusicSheetAuthRecord;
import com.yonge.cooleshow.biz.dal.enums.AuthStatusEnum;
import com.yonge.cooleshow.biz.dal.service.MusicSheetAuthRecordService;
import com.yonge.toolset.base.exception.BizException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;


@Service
public class MusicSheetAuthRecordServiceImpl extends ServiceImpl<MusicSheetAuthRecordDao, MusicSheetAuthRecord> implements MusicSheetAuthRecordService {


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean audit(TeacherMusicSheetAuditReq param, Long userId) {

        // 删除审核中的状态
        this.lambdaUpdate()
                .eq(MusicSheetAuthRecord::getMusicSheetId,param.getMusicSheetId())
                .eq(MusicSheetAuthRecord::getAuditState, AuthStatusEnum.DOING.getCode())
                .remove();

        MusicSheetAuthRecord musicSheetAuthRecord = new MusicSheetAuthRecord();
        musicSheetAuthRecord.setMusicSheetId(param.getMusicSheetId());
        musicSheetAuthRecord.setCreateTime(new Date());
        musicSheetAuthRecord.setAuditState(param.getAuthStatus());
        musicSheetAuthRecord.setReason(param.getRemark());
        musicSheetAuthRecord.setVerifyUserId(userId);
        return this.saveOrUpdate(musicSheetAuthRecord);
    }

    @Override
    public void setAuditDoing(Long musicSheetId) {
        List<MusicSheetAuthRecord> list = this.lambdaQuery()
                                              .eq(MusicSheetAuthRecord::getMusicSheetId, musicSheetId)
                                              .eq(MusicSheetAuthRecord::getAuditState, AuthStatusEnum.DOING.getCode())
                                              .list();
        if (!CollectionUtils.isEmpty(list)) {
            return;
        }
        MusicSheetAuthRecord musicSheetAuthRecord = new MusicSheetAuthRecord();
        musicSheetAuthRecord.setMusicSheetId(musicSheetId);
        musicSheetAuthRecord.setAuditState(AuthStatusEnum.DOING);
        this.saveOrUpdate(musicSheetAuthRecord);
    }

    @Override
    public String selectAuditReason(Long musicSheetId) {
        MusicSheetAuthRecord one = this.lambdaQuery()
                                       .eq(MusicSheetAuthRecord::getMusicSheetId, musicSheetId)
                                       .orderByDesc(MusicSheetAuthRecord::getId)
                                       .last("limit 1")
                                       .one();
        if (one == null) {
            return "";
        }
        return one.getReason();

    }
}