package com.fjhx.oa.service.work.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjhx.common.constant.SourceConstant;
import com.fjhx.file.entity.ObsFile;
import com.fjhx.file.utils.ObsFileUtil;
import com.fjhx.oa.entity.work.dto.WorkTasksDto;
import com.fjhx.oa.entity.work.dto.WorkTasksSelectDto;
import com.fjhx.oa.entity.work.po.WorkTasks;
import com.fjhx.oa.entity.work.vo.WorkTasksVo;
import com.fjhx.oa.mapper.work.WorkTasksMapper;
import com.fjhx.oa.service.work.WorkTasksService;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.wrapper.IWrapper;
import com.ruoyi.system.utils.UserUtil;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * <p>
 * 工作任务 服务实现类
 * </p>
 *
 * @author
 * @since 2023-04-07
 */
@DS(SourceConstant.OA)
@Service
public class WorkTasksServiceImpl extends ServiceImpl<WorkTasksMapper, WorkTasks> implements WorkTasksService {

    @Override
    public Page<WorkTasksVo> getPage(WorkTasksSelectDto dto) {
        IWrapper<WorkTasks> wrapper = getWrapper();
        wrapper.orderByDesc("wt", WorkTasks::getId);
        Long userId = SecurityUtils.getUserId();
        wrapper.and(w -> w.eq(WorkTasks::getCreateUser, userId).or().eq(WorkTasks::getPersonLiableId, userId));
        wrapper.eq(WorkTasks::getSource, dto.getSource());
        wrapper.eq(WorkTasks::getStatus, dto.getStatus());
        wrapper.like(WorkTasks::getTitle, dto.getKeyword());
        Page<WorkTasksVo> page = this.baseMapper.getPage(dto.getPage(), wrapper);
        List<WorkTasksVo> records = page.getRecords();
        UserUtil.assignmentNickName(records, WorkTasks::getCreateUser, WorkTasksVo::setPublisherName);
        UserUtil.assignmentNickName(records, WorkTasks::getPersonLiableId, WorkTasksVo::setPersonLiableName);
        return page;
    }

    @Override
    public WorkTasksVo detail(Long id) {
        WorkTasks WorkTasks = this.getById(id);
        WorkTasksVo result = BeanUtil.toBean(WorkTasks, WorkTasksVo.class);
        return result;
    }

    @DSTransactional
    @Override
    public void add(WorkTasksDto workTasksDto) {
        List<ObsFile> fileList = workTasksDto.getFileList();
        workTasksDto.setStatus(0);
        workTasksDto.setSource(0);
        workTasksDto.setFileName(fileList.get(0).getFileName());
        this.save(workTasksDto);
        ObsFileUtil.saveFile(fileList, workTasksDto.getId());
    }

    @Override
    public void edit(WorkTasksDto workTasksDto) {
        this.updateById(workTasksDto);
    }

    @Override
    public void delete(Long id) {
        this.removeById(id);
    }

}
