package com.fkzy.warn.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fkzy.warn.mapper.AnnouncementMapper;
import com.fkzy.warn.model.Announcement;
import com.fkzy.warn.service.AnnouncementService;
import com.fkzy.warn.common.constants.EntityConstants;
import com.fkzy.warn.common.request.RequestParameter;
import com.fkzy.warn.common.response.ApiResponse;
import com.fkzy.warn.model.User;
import com.fkzy.warn.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * @author zhangjing
 * @date 2023/10/16 18:17
 * @description
 */
@Service
public class AnnouncementServiceImpl extends ServiceImpl<AnnouncementMapper, Announcement> implements
    AnnouncementService {

    @Autowired
    private UserService userService;

    @Override
    public ApiResponse saveModel(Announcement entity, String ticket) {
        save(entity);
        return new ApiResponse();
    }

    @Override
    public ApiResponse updateModel(Announcement entity,String ticket) {
        this.updateById(entity);
        return new ApiResponse();
    }

    @Override
    public ApiResponse deleteModel(List<String> ids) {
        Announcement entity = new Announcement();
        entity.setIsDel(EntityConstants.DEL);
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.in("id", ids);
        update(entity, wrapper);
        return new ApiResponse();
    }

    @Override
    public Page<Announcement> queryPage(RequestParameter parameter) {
        Announcement entity = parameter.getParameter().toJavaObject(Announcement.class);
        Page<Announcement> page = new Page<Announcement>(parameter.getCurrent(), parameter.getSize());
        page.setSearchCount(true);
        page.setOptimizeCountSql(true);
        QueryWrapper<Announcement> eWrapper = new QueryWrapper<Announcement>(entity);
        Page<Announcement> result = this.page(page, eWrapper);
        return result;
    }

    @Override
    public ApiResponse release(Announcement entity, String ticket) {
        ApiResponse response =  new ApiResponse();
        User user = userService.getUserByTicket(ticket);
        if (user == null) {
            response.recordError(501);
            return response;
        }
        entity.setReleasedTime(new Date());
        entity.setReleasedUserId(user.getId());
        entity.setReleasedUserName(user.getBusinessPerson());
        updateById(entity);
        return response;
    }
}
