package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.domain.Taskson;
import com.example.demo.domain.User;
import com.example.demo.mapper.TasksonMapper;
import com.example.demo.mapper.UserMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.http.impl.bootstrap.HttpServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.*;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

@Tag(name = "任务上传", description = " ")
@RestController
public class TaskuploadController {
    @Autowired
    private TasksonMapper tasksonMapper;
    @Autowired
    private UserMapper userMapper;

    @RequestMapping(value = "/taskupload", method = RequestMethod.POST)
    @Operation(summary = "任务上传接口")
    public String taskupload(HttpServletRequest request,
                             @RequestParam(name = "skey", required = true) String skey) {
        //skey 查表

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("skey", skey);
        User user = this.userMapper.selectOne(queryWrapper);
        System.out.println(user);
        QueryWrapper<Taskson> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.like("studentnumber", user.getStudentNumber());
        queryWrapper1.like("Task_id", 1); //任务表（需修改）
        Taskson taskson = this.tasksonMapper.selectOne(queryWrapper1);
        if (taskson == null) {
            taskson = new Taskson();
            taskson.setTaskid(1);//任务id（需修改）
            taskson.setStudentnumber(user.getStudentNumber());
            this.tasksonMapper.insert(taskson);
        }
        //文件接收
        taskson = this.tasksonMapper.selectOne(queryWrapper1);
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        String type = files.get(0).getOriginalFilename().split("\\.")[1];
        MultipartFile file = null;
        FileOutputStream stream = null;
        Path fapath = Paths.get("E:\\git\\project\\src\\demo\\target" + "\\" + taskson.getTaskid());
        try {
            Files.createDirectories(fapath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String path = "E:\\git\\project\\src\\demo\\target" + "\\" + taskson.getTaskid() + "\\" + taskson.getStudentnumber() + "." + type;


        try {
            stream = new FileOutputStream(path);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            if (!file.isEmpty()) {
                try {
                    byte[] bytes = file.getBytes();

                    stream.write(bytes);
                    stream.close();
                } catch (Exception e) {
                    stream = null;
                    return "You failed to upload " + i + " => "
                            + e.getMessage();
                }
            } else {
                return "You failed to upload " + i
                        + " because the file was empty.";
            }
        }
        System.out.println("upload success");
        taskson.setFilepath(path);
        this.tasksonMapper.updateById(taskson);
        return "upload successful";

    }


}
