package com.qxgmat.controller.api;

import com.nuliji.tools.ResponseHelp;
import com.nuliji.tools.exception.SystemException;
import com.qxgmat.data.dao.entity.Ad;
import com.qxgmat.dto.request.SmsSendDto;
import com.qxgmat.dto.response.UploadInfoDto;
import com.qxgmat.help.CaptchaHelp;
import com.qxgmat.help.SmsHelp;
import com.qxgmat.help.UploadHelp;
import com.nuliji.tools.MessageHelp;
import com.nuliji.tools.Response;
import com.nuliji.tools.exception.ParameterException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * Created by GaoJie on 2017/11/3.
 */

@RestController
@RequestMapping("/api/common")
@Api(tags = "通用", description = "通用接口")
public class CommonController {

    @Value("${upload.local_path}")
    private String localPath;

    @Value("${upload.web_url}")
    private String webUrl;

    @Autowired
    private SmsHelp smsHelp;

    @Autowired
    private CaptchaHelp captchaHelp;

    @Autowired
    private UploadHelp uploadHelp;


//    @RequestMapping(value = "/sms/register", method = RequestMethod.POST)
//    @ApiOperation(value = "注册验证码", notes = "相关接口验证后失效", httpMethod = "POST")
//    public Response<Boolean> sendSmsRegister(@RequestBody @Validated SmsSendDto smsSendDto, HttpSession session) {
//        boolean result = smsHelp.sendCode(smsSendDto.getMobile(), smsHelp.REGISTER_TEMPLATE, session);
//        return MessageHelp.success(result);
//    }
//
//    @RequestMapping(value = "/sms/forget", method = RequestMethod.POST)
//    @ApiOperation(value = "忘记密码验证码", notes = "相关接口验证后失效", httpMethod = "POST")
//    public Response<Boolean> sendSmsForget(@RequestBody @Validated SmsSendDto smsSendDto, HttpSession session) {
//        boolean result = smsHelp.sendCode(smsSendDto.getMobile(), smsHelp.FORGET_TEMPLATE, session);
//        return MessageHelp.success(result);
//    }

    @RequestMapping(value = "/sms/valid", method = RequestMethod.POST)
    @ApiOperation(value = "短信验证码", notes = "相关接口验证后失效", httpMethod = "POST")
    public Response<Boolean> sendSmsValid(@RequestBody @Validated SmsSendDto smsSendDto, HttpSession session) {
        boolean result = smsHelp.sendCode(smsSendDto.getMobile(), smsHelp.VALID_TEMPLATE, session);
        return MessageHelp.success(result);
    }

//    @RequestMapping(value = "/captcha/image", produces = MediaType.IMAGE_JPEG_VALUE, method = RequestMethod.GET)
//    @ApiOperation(value = "图形验证码", notes = "相关接口验证后失效", httpMethod = "GET")
//    public void captcha(HttpSession session, HttpServletResponse response) throws IOException {
//        BufferedImage image = captchaHelp.createImage(session);
//        response.setContentType(MediaType.IMAGE_JPEG_VALUE);
//        ImageIO.write(image, "jpeg", response.getOutputStream());
//    }
//
//    @RequestMapping(value = "/upload/authorize/{type}", method = RequestMethod.GET)
//    @ApiOperation(value = "上传授权", notes = "上传至oss的授权信息", httpMethod = "GET")
//    public Response<UploadInfoDto> uploadAuthorize(
//            @NotBlank @PathVariable("type") @ApiParam(value = "文件类型", allowableValues = "file,image") String type,
//            @NotBlank @RequestParam("module") @ApiParam(value = "模块", allowableValues = "plan,user,operate,other") String module,
//            @RequestParam(defaultValue = "1024") @ApiParam(value = "尺寸,单位kb") int size,
//            HttpSession session) {
//        switch (type){
//            case "file":
//                type = uploadHelp.UPLOAD_FILE;
//                break;
//            case "image":
//                type = uploadHelp.UPLOAD_IMAGE;
//                break;
//            default:
//                throw new ParameterException("文件类型错误");
//        }
//        if(size < 1 && size>10240){
//           throw new ParameterException("文件尺寸异常");
//        }
//        size *= 1024;
//        switch(module){
//            case "plan":
//            case "user":
//            case "operate":
//            case "other":
//                break;
//            default:
//                throw new ParameterException("存储模块错误");
//        }
//        UploadInfoDto uploadInfoDto = uploadHelp.authorize(type, module, size);
//        return MessageHelp.success(uploadInfoDto);
//    }

    @RequestMapping(value = "/upload/image", produces = MediaType.IMAGE_JPEG_VALUE, method = RequestMethod.POST)
    @ApiOperation(value = "上传文件", notes = "上传至本地服务器", httpMethod = "POST")
    public Response<String> uploadImage(@RequestParam("file") MultipartFile multipartFile)  {
        if (multipartFile.isEmpty()) {
            throw new ParameterException("上传文件为空");
        }
        String filename = multipartFile.getOriginalFilename();
        String suffix = filename.substring(filename.lastIndexOf(".")+1);
        String contentType = multipartFile.getContentType();
        if (!contentType.contains("")) {
            throw new ParameterException("文件类型错误");
        }
        // todo 随机文件名
        String file = UUID.randomUUID().toString()+"."+suffix;
        try {
            File dir = new File(localPath);
            File dest = new File(dir.getAbsolutePath() + File.separator+file);

            multipartFile.transferTo(dest);
            return ResponseHelp.success(webUrl+file);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseHelp.exception(new SystemException("图片上传失败"));
        }
    }
}
