package com.hssx.pcbms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hssx.pcbms.entity.TaskFile;
import com.hssx.pcbms.mapper.TaskFileMapper;
import com.hssx.pcbms.mapper.UserMapper;
import com.hssx.pcbms.service.TaskFileService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hssx.pcbms.util.HttpRespMsg;
import com.hssx.pcbms.util.PageUtil;
import com.hssx.pcbms.util.UploadFileToFileNameUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 吴涛涛
 * @since 2019-11-11
 */
@Service
public class TaskFileServiceImpl extends ServiceImpl<TaskFileMapper, TaskFile> implements TaskFileService {

    @Resource
    private TaskFileMapper taskFileMapper;
    @Value("${upload.path}")
    private String path;
    @Resource
    private UserMapper userMapper;
    @Override
    public HttpRespMsg updateFile(MultipartFile file,TaskFile taskFile) {
        HttpRespMsg msg = new HttpRespMsg();
        String filePath = "";
        if (file != null) {
            filePath = UploadFileToFileNameUtil.uploadFile(file, path);
        }
        if(filePath.equals("")){
            msg.setError("上传图片失败了");
            return msg;
        }
        taskFile.setUploader(userMapper.selectById(taskFile.getUploaderId()).getName());
        taskFile.setName(file.getOriginalFilename());
        taskFile.setUrl(filePath);
        taskFile.setTaskId(taskFile.getTaskId());
        taskFileMapper.insert(taskFile);
        msg.data = filePath;
        return msg;
    }

    @Override
    public HttpRespMsg getList(PageUtil page, String taskId) {
        HttpRespMsg msg = new HttpRespMsg();
        PageHelper.startPage(page.getPageNum(),page.getPageSize());
        List<TaskFile> list = taskFileMapper.selectList(new QueryWrapper<TaskFile>().eq("task_id", taskId).orderByDesc("id"));
        PageInfo<TaskFile> info = new PageInfo<>(list);
        msg.data = info;
        return msg;
    }

    @Override
    public HttpRespMsg delById(TaskFile taskFile) {
        HttpRespMsg msg = new HttpRespMsg();
        TaskFile oldtaskFile = taskFileMapper.selectById(taskFile.getId());
        if(taskFile.getUploaderId().equals(oldtaskFile.getUploaderId())){
            taskFileMapper.deleteById(oldtaskFile.getId());
        }else{
            msg.setError("您不具备删除该文件的");
        }
        return msg;
    }
}
