package com.mx.cneeds.server.datashow.web.wechat;

import com.alibaba.fastjson.JSON;
import com.mx.cneeds.common.constant.FilePath;
import com.mx.cneeds.common.result.R;
import com.mx.cneeds.common.result.WebSocketConnectionResult;
import com.mx.cneeds.server.wechat.common.dispatcher.MessageDispatcher;
import com.mx.cneeds.server.wechat.common.json.WechatJsonMessage;
import com.mx.cneeds.server.wechat.websocket.config.NettyChannelManager;
import com.mx.hbasefile.hadoop.hdfs.api.HdfsTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @ClassName WechatController
 * @Author zzrdark
 * @Date 2020-04-22 16:29
 * @Description TODO
 **/
@Controller
@Slf4j
@RequestMapping("/wechat")
public class WechatController {

    @Autowired
    private HdfsTemplate hdfsTemplate;

    @Autowired
    private MessageDispatcher messageDispatcher;

    @Autowired
    private NettyChannelManager nettyChannelManager;

    @RequestMapping("/wechatFileUpload")
    @ResponseBody
    public R upload(HttpServletRequest httpServletRequest, MultipartFile file) throws IOException {

        StringBuffer dir = new StringBuffer(FilePath.wechatFilePath);
        // 1. 读取系统时间
        Calendar calendar = Calendar.getInstance();
        Date time = calendar.getTime();

        // 2. 格式化系统时间
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        String fileName = format.format(time);
        dir.append(fileName);
        hdfsTemplate.saveFile(dir.toString(),file.getOriginalFilename(),file.getInputStream(),file.getSize(), (short) 2);
        String sufUrl = httpServletRequest.getScheme() +"://" +
                httpServletRequest.getServerName() + ":" +
                httpServletRequest.getServerPort()+
                "/wechat/wechatDownload/"+fileName+"/"
                +file.getSize()+"/"+file.getOriginalFilename();
        return R.ok().put("data",sufUrl);
    }

    @RequestMapping("/wechatDownload/{dir}/{fileSize}/{fileName}")
    public void download(@PathVariable("dir") String dir, @PathVariable("fileName") String fileName,
                         @PathVariable("fileSize") String fileSize, HttpServletResponse response) throws IOException {
        StringBuffer dirPath = new StringBuffer(FilePath.wechatFilePath);
        dirPath.append(dir);
        InputStream inputStream = hdfsTemplate.openFile(dirPath.toString(), fileName);

        ServletOutputStream outputStream = response.getOutputStream();
        String mediaType = fileName.substring(fileName.indexOf("."));
        response.setContentType(mediaType);
        response.addHeader("Content-Disposition", "attachment; filename" + "testfilename");


        byte[] bytes = new byte[1024];
        long total = Long.valueOf(fileSize);
        while (total>0) {
            inputStream.read(bytes);
            outputStream.write(bytes,0, total>1024?1024: (int) total);
            outputStream.flush();
            total-=1024;
        }
        outputStream.close();
    }

    @RequestMapping("/wechatMessageHttp")
    @ResponseBody
    public void wechatMessageHttp(@RequestBody WechatJsonMessage jsonMessage){
            messageDispatcher.doWechatDispatcher(jsonMessage);
    }

    @RequestMapping("/getWebSocketConnection")
    @ResponseBody
    public WebSocketConnectionResult getWebSocketConnection(){
        WebSocketConnectionResult R = new WebSocketConnectionResult();

        R.setConnections(nettyChannelManager.getChannelsWcIds());
        R.setTotal((long) R.getConnections().size());

        return R;
    }
}
