package com.sysu.admin.controller.upload;

import com.sysu.admin.support.base.ServiceContext;
import com.sysu.admin.utils.TextUtil;
import com.xiesx.fastboot.base.result.BaseResult;
import com.xiesx.fastboot.base.result.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RequestMapping("/uploadRecord")
@Controller
public class UploadRecordController extends ServiceContext {

    @Autowired
    UploadRecordRepository mUploadRecordRepository;

    /**
     * 上传图片
     */
    @RequestMapping("uploadImg")
    @ResponseBody
    public BaseResult uploadImg(@RequestParam("file") MultipartFile file) {
        if(file != null) {
            String imageDirPath =  mSConfigService.getV("imageDirPath");
            String hz = TextUtil.rightSubstring(".",file.getOriginalFilename());
            String newFileName = System.currentTimeMillis() + "_" + mShiroService.getPrincipalId()+"." + hz;
            try {
                //复制到零时文件
                File target = new File(imageDirPath + newFileName);
                file.transferTo(target);
            } catch (IOException e) {
                e.printStackTrace();
            }
            UploadRecord uploadRecord = new UploadRecord().setFilename(newFileName);
            mUploadRecordRepository.save(uploadRecord);
            Map<String,Object> map = new HashMap();
            map.put("filename",newFileName);
            map.put("id",uploadRecord.getId());
            map.put("type",hz);
            return R.succ(map);
        }else {
            return R.fail();
        }
    }

}
