package com.example.action;

import com.example.frame.base.FileUploadResponse;
import com.example.frame.base.BaseResponse;
import com.example.frame.base.ErrorType;
import com.example.frame.base.Screen;
import com.example.frame.utils.LocalData;
import com.example.config.ActionConfig;
import com.example.frame.utils.MapperUtil;
import org.springframework.beans.BeansException;
import org.apache.commons.io.FileUtils;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 全局请求Controller，如果无特殊请求，则不需再增加其他Controller
 * 全局htm后缀入口{@link GlobalController#hold}
 * 全局异常捕捉{@link GlobalController#excepitonHandler}
 * 全局上传接口{@link GlobalController#upload}
 * 全局下载接口{@link GlobalController#download}
 * <p>
 * 说明Request命名规则，驼峰式命名
 * Api#Example#Request ==> 目标#动作#Request
 *
 * @author author
 * @version 0.0.1
 * @since 2019-06-16
 */
@Controller
@ControllerAdvice
public class GlobalController implements ErrorController {

    @Value("${web.welcome.page}")
    private String homePage;

    /**
     * 全局异常捕捉
     *
     * @param request
     * @param response
     * @param exception 要捕获的异常
     * @return
     */
    @ExceptionHandler(Exception.class)
    public String excepitonHandler(HttpServletRequest request, HttpServletResponse response, Model model, Exception exception) {
        StringBuffer msg = new StringBuffer("");
        if (exception != null) {
            msg = new StringBuffer("");
            String message = exception.toString();
            int length = exception.getStackTrace().length;
            if (length > 0) {
                msg.append("<a>").append(message).append("</a><br>");
                for (int i = 0; i < length; i++) {
                    msg.append("<a>").append(exception.getStackTrace()[i]).append("</a><br>");
                }
            } else {
                msg.append(message);
            }
        }
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        model.addAttribute("msg", msg.toString());
        return "500";
    }

    private final static String ERROR_PATH = "/error";

    @Override
    public String getErrorPath() {
        return ERROR_PATH;
    }

    @RequestMapping(value = ERROR_PATH)
    public String error(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");

        switch (statusCode) {
            case 404:
                return "404";
            case 403:
                try {
                    LocalData.getResponse().sendRedirect("/login.htm");
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return "403";
            case 500:
                return "500";
            default:
                return "403";
        }
    }

    @RequestMapping("/")
    public String home() {
        return "forward:" + homePage;
    }

    /**
     * 当未明确指定控制器时，走该请求，默认返回对应的layout布局和screen视图
     * 当需要使用layout时，不需要返回值，ViewNameTranslator会处理对应关系
     *
     * @param model
     * @param request
     */
    @RequestMapping({"/**/*.htm"})
    public void hold(HttpServletRequest request, Model model) {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();

        // 尝试执行Target Screen执行器(服务器渲染)，不存在则直接返回视图模板(Ajax渲染)
        Screen screenExec = null;
        try {
            String target = LocalData.getTarget();
            target = target.replaceAll("/", ".").toLowerCase();
            screenExec = LocalData.getApplicationContext().getBean(ActionConfig.SCREEN_PREFIX + target, Screen.class);
            screenExec.exec(model, request, response);
        } catch (BeansException e) {

        }

        //todo 可在此获取共性数据(也可以在全局拦截器GlobalHandlerInterceptor、拦截器作用域比此更高)，
        //todo 例如用户信息等。其他业务数据在页面渲染后通过Ajax请求
    }

    @RequestMapping("/upload")
    @ResponseBody
    public BaseResponse upload(HttpServletRequest request) {
        FileUploadResponse fileUploadResponse = new FileUploadResponse();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
        MultipartFile target = multipartHttpServletRequest.getFile("file");

        String fileName = target.getOriginalFilename();

        //========
        //处理文件
        //========
        fileUploadResponse.setId(1L);
        fileUploadResponse.setUrl("example.com\\img\\1.jpg");
        fileUploadResponse.setDownloadUrl("example.com\\img\\1.jpg");


        if (target != null) {
            fileUploadResponse.addError(ErrorType.BUSINESS_ERROR, "文件上传成功,但未处理文件[" + fileName + "]!");
        } else {
            fileUploadResponse.addError(ErrorType.BUSINESS_ERROR, "文件上传失败!");
        }

        return fileUploadResponse;
    }

    @RequestMapping("/download")
    @ResponseBody
    public ResponseEntity<byte[]> download(@RequestParam(value = "file", required = false) String file) throws IOException {

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        //========
        //下载DEMO
        //========
        if (file == null) {
            file = "test.txt";
            headers.setContentDispositionFormData("attachment", new String(file.getBytes("UTF-8"), "iso-8859-1"));
            return new ResponseEntity<byte[]>("test".getBytes(),
                    headers, HttpStatus.CREATED);
        }

        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(new File(file)),
                headers, HttpStatus.CREATED);
    }

    private static ConcurrentHashMap<String, SseEmitter> sseMap = new ConcurrentHashMap();

    /**
     * Sse推送服务，服务器向js推送自定义消息
     * Sse容器{@link GlobalController#sseMap}
     * Sse批量推送{@link GlobalController#pushAll}
     */
    @RequestMapping(value = "/sse/{userId}", produces = "text/event-stream;charset=UTF-8")
    public SseEmitter sse(@PathVariable String userId) {
        SseEmitter sseEmitter = new SseEmitter(10000000L);
        sseEmitter.onError(new Consumer<Throwable>() {
            private String key = userId;

            @Override
            public void accept(Throwable throwable) {
                sseMap.remove(key);
            }
        });
        sseEmitter.onCompletion(new Runnable() {
            private String key = userId;

            @Override
            public void run() {
                sseMap.remove(key);
            }
        });
        if (sseMap.get(userId) != null) {
            sseMap.remove(userId);
        }
        sseMap.put(userId, sseEmitter);

        return sseEmitter;
    }

    /**
     * Sse批量推送
     *
     * @param data 推送对象
     */
    public void pushAll(Object data) {
        for (String s : sseMap.keySet()) {
            try {
                sseMap.get(s).send(MapperUtil.toJson(data), MediaType.APPLICATION_JSON);
            } catch (IOException e) {
                sseMap.remove(s);
            }
        }
    }
}
