package com.aiup.api.controller;


import com.aiup.service.domain.R;
import com.aiup.service.entity.UserAdvice;
import com.aiup.service.service.UserAdviceService;
import com.aiup.service.utils.LoginUserUtils;
import com.aiup.service.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Date;
import java.util.UUID;

@Api(tags = "问题建议相关接口")
@RestController
@RequestMapping("/v1/advice")
@RequiredArgsConstructor
public class UserAdviceController {


    @Value("${upload.adviceFileDir}")
    private String uploadFileDir;
    @Value("${upload.adviceFileUrl}")
    private String fileUrl ;
    @Autowired
    private UserAdviceService userAdviceService;

    @ApiOperation(value = "新增建议",notes = "客户端用form表单进行提交," +
            "其中包含两个字段：" +
            "1. file 类型：MultipartFile;" +
            "2. advice 类型： String")
    @PostMapping("/create")
    public R<Boolean> create(HttpServletRequest request,@RequestParam(value = "file",required = false) MultipartFile file) {
        String url =null;
        String msg = request.getParameter("advice");
        if(StringUtils.isEmpty(msg)){
            return R.error("请输入您的宝贵意见后再进行提交");
        }
        Integer userId = LoginUserUtils.getLoginUser().getUserId();
        if(file != null){
            // 获取原始文件名
            String originalFilename = file.getOriginalFilename();
            // 生成新的文件名，以防止文件名冲突
            String newFilename = UUID.randomUUID().toString() + "_" + originalFilename;
            File dir = new File(uploadFileDir);
            if(!dir.exists()){
                dir.mkdirs();
            }
            // 文件保存路径
            String filePath = uploadFileDir + newFilename;
            // 保存文件到服务器
            try {
                file.transferTo(new File(filePath));
            }
            catch (Exception ep)
            {
                ep.printStackTrace();
                return R.error("文件保存失败，请联系管理员");
            }
            url = fileUrl+newFilename;
        }
        UserAdvice userAdvice = new UserAdvice();
        userAdvice.setImageList(url);
        userAdvice.setAdvice(msg);
        userAdvice.setCreateTime(new Date());
        userAdvice.setUserId(userId);
        userAdviceService.insert(userAdvice);
        return R.ok(true);
    }
}
