package com.yutou.nas.Controllers;

import com.alibaba.fastjson.JSONObject;
import com.yutou.nas.interfaces.DownloadInterface;
import com.yutou.nas.utils.QQBotManager;
import com.yutou.nas.utils.Tools;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
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;

@Controller
@RequestMapping("/qq/bot")
public class QQBot {
    @RequestMapping("test.do")
    @ResponseBody
    public String test(){
        return "123";
    }

    @RequestMapping("send.do")
    @ResponseBody
    public String send(String msg,String imgUrl){
        JSONObject json=new JSONObject();
        try {
            String ret;
            if(StringUtils.isEmpty(imgUrl)){
                ret= QQBotManager.getInstance().sendMessage(msg);
            }else{
                Tools.download(imgUrl, new DownloadInterface() {
                    @Override
                    public void onDownload(File file) {
                        super.onDownload(file);
                        QQBotManager.getInstance().sendMessage(file,msg);
                    }

                    @Override
                    public void onError(Exception e) {
                        super.onError(e);
                        QQBotManager.getInstance().sendMessage(imgUrl+"\n"+msg);
                    }
                });
                ret="图片下载中";
            }
            json.put("code",0);
            json.put("msg",ret);
        }catch (Exception e){
            e.printStackTrace();
            json.put("code",-1);
            json.put("msg",e.getMessage());
        }
       return json.toJSONString();
    }
    @RequestMapping("sendAndImg.do")
    @ResponseBody
    public String botMsg(String msg,@RequestParam("file") MultipartFile file){
        JSONObject json=new JSONObject();
        if(file==null){
            json.put("code",-1);
            json.put("msg","图片为空");
            return json.toJSONString();
        }
        String ret;
        try {
            String path = Tools.createFile("qq_image",file, file.getName());
            ret=QQBotManager.getInstance().sendMessage(new File(path),msg);
        } catch (Exception e) {
            e.printStackTrace();
            ret=e.getLocalizedMessage();
        }
        json.put("code",0);
        json.put("msg",ret);
        return json.toJSONString();
    }
}
