package com....;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
/*
 * @describe 上传头像文件,上传文件夹需存在
 */
@Controller
public class ThenHeadPortraitController  {
                       
    private final int MAX_SIZE = 1024 * 1024 * 1;   //限制用户头像的最大值为1M
    private String[] extendNamesArray = {".jpg",".jpeg"};   //用户头像的扩展名数组,方面验证
    private String rootPath;                    //文件根路径
    private String p_w_picpathNewPath;        //头像新路径(包含头像名以及扩展名)
    private String p_w_picpathOldPath;        //头像在数据库中的原有路径(包含头像名以及扩展名)
    private String p_w_picpathNames;          //头像的新名字(时间+用户名),时间精确到毫秒
    private String extendName ;         //头像的扩展名,进行扩展名验证,以达到对用户头像的图片类型限制
    private String message;                 //用于返回上传头像的信息
    private String p_w_picpathURL;                //用于返回用户头像存放的物理路径
    private MultipartFile p_w_picpathFile;
                       
//测试时使用方法 
    @RequestMapping(value="/then/uploadHeadPortrait.jspx",method= RequestMethod.GET)
    public void  upload(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
    {
        request.getRequestDispatcher("../MyJsp.jsp").forward(request,response);
        return;
    }
    @RequestMapping(value="/then/uploadHeadPortrait.jspx",method= RequestMethod.POST)
    @ResponseBody
    public Map<String,String> uploadHeadPortrait(String account,HttpServletRequest request){
        String p_w_picpathAccount = account;      //存储用户临时的用户名,以便进行文件的命名
        Map<String,String> map = new HashMap<String,String>();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        //获取上传头像
        p_w_picpathFile = multipartRequest.getFile("file");
        //获取上传头像的文件名
        String fileName = p_w_picpathFile.getOriginalFilename();
        System.out.println("OriginalFilename:"+fileName);
        //获取文件扩展名
        extendName = fileName.substring(fileName.lastIndexOf("."));
        //获取上传头像的大小
        int p_w_picpathSize = (int) p_w_picpathFile.getSize();
        //验证头像的扩展名是否符合要求
        if((extendName.equals(extendNamesArray[0])||extendName.equals(extendNamesArray[1]))&&(p_w_picpathSize<=MAX_SIZE)){
            rootPath =  request.getSession().getServletContext().getRealPath("//upload");
            System.out.println("rootPath:"+rootPath);
            p_w_picpathNames = getUploadCurrentTime() + p_w_picpathAccount; //重新命名上传头像名称
            System.out.println("p_w_picpathNames:"+p_w_picpathNames);
            p_w_picpathNewPath = rootPath+"\\"+p_w_picpathNames+extendName;
            System.out.println("p_w_picpathNewPath:"+p_w_picpathNewPath);
            //判断新路径是否等于数据库中已存在的路径,不等于,则存储新路径,删除原有头像文件
            if(!p_w_picpathNewPath.equals(getDatabaseImageOldPath(p_w_picpathAccount))){
                if(getDatabaseImageOldPath(p_w_picpathAccount)!=null&&getDatabaseImageOldPath(p_w_picpathAccount)!=""){
                    File file = new File(getDatabaseImageOldPath(p_w_picpathAccount));
                    if(p_w_picpathSave(p_w_picpathAccount,p_w_picpathNewPath)){
                        if(file.exists()){
                            file.delete();
                        }
                        message = "头像上传成功";
                        p_w_picpathURL = p_w_picpathNewPath;
                        map.put("message",message);
                        map.put("p_w_picpathURL",p_w_picpathURL);
                    }else{
                        //保存失败
                        message = "头像保存失败";
                        p_w_picpathURL = null;
                        map.put("message",message);
                        map.put("p_w_picpathURL",p_w_picpathURL);
                                           
                    }
                                       
                }
                                   
            }else{
                message = "头像上传失败";
                p_w_picpathURL = null;
                map.put("message",message);
                map.put("p_w_picpathURL",p_w_picpathURL);
            }
                               
        }else{      //图像格式不符合或者头像的大小大于1M
            message = "头像上传失败,格式或大小不符合";
            p_w_picpathURL = null;
            map.put("message",message);
            map.put("p_w_picpathURL",p_w_picpathURL);
        }
        return map;
    }
    //获取头上上传的当前时间
    private String getUploadCurrentTime(){
        return new SimpleDateFormat("yyyyMMddHHmmssSSS") .format(new Date() );
    }
    //获取数据库中原有路径,如有则返回路径,否则返回可能为空或“”
    private String getDatabaseImageOldPath(String account){
        UserDetail userDetatilOldPath=userService.findByUsername(account).getDetail();
        p_w_picpathOldPath =  userDetatilOldPath.getAvatar();
        return p_w_picpathOldPath;
    }
    //对原有头像的新路径进行存储,存储后进行检查,时候已经存储,存储成功返回true,失败则返回false
    private boolean p_w_picpathSave(String account,String p_w_picpathNewPath){
        File uploadFile = new File(p_w_picpathNewPath);
        try {
            FileCopyUtils.copy(p_w_picpathFile.getBytes(), uploadFile);
            FileUtils.copyInputStreamToFile(p_w_picpathFile.getInputStream(), new File(p_w_picpathNewPath));
            UserDetail ud=userService.findByUsername(account).getDetail();
            ud.setAvatar(p_w_picpathNewPath);     //设置头像新路径
            userDetailService.update(ud) ;      //对头像进行数据库更新操作
            if(getDatabaseImageOldPath(account)!=null||getDatabaseImageOldPath(account).equals("")){
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("【上传头像失败...】");
            return false;
        }
        return false;
    }
    @Autowired
    private UserDetailService userDetailService;
    @Autowired
    private UserService userService;
}