package com.bohuikeji.frame.module.admin.controller.su;

import com.bohuikeji.frame.module.admin.entity.vo.ShortUrlVo;
import com.bohuikeji.frame.module.admin.service.IRoutingDelegate;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
import com.bohuikeji.frame.module.admin.utils.UrlUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * 短链接处理类
 * @author Admin
 */
@Slf4j
@RestController
@RequestMapping("/su")
@RequiredArgsConstructor
public class ShortUrl {
    final IRoutingDelegate routingDelegate;
    private static final String URL_404="https://supply.h5.tcjskd.com/404/index.html";

    /**
     * 短链接解析
     * @param pixUrl 短地址后缀
     * @return
     */
    @RequestMapping(value = "/{pixUrl}",produces = MediaType.TEXT_PLAIN_VALUE,method = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE})
    Object analysis(@PathVariable String pixUrl, HttpServletRequest request, HttpServletResponse response) throws IOException, URISyntaxException {
        ShortUrlVo url=UrlUtils.getSortUrlVo(pixUrl);
        if(url==null){
            if(StringUtils.isBlank(request.getHeader("User-Agent"))){
                return new ResponseEntity<String>("该链接已失效", HttpStatus.INTERNAL_SERVER_ERROR);
            }
            log.error("404短链接：{}，重定向到：{}",pixUrl,URL_404);
            return new ModelAndView("redirect:"+URL_404);
        }
        //重定向
        if(url.getRedirect()){
            log.error("短链接：{}，重定向到：{}",pixUrl,url.getRealUrl());
            return new ModelAndView("redirect:"+url.getRealUrl());
        }
        log.error("短链接：{}，转发到：{}",pixUrl,url.getRealUrl());
        //请求转发
        return routingDelegate.redirect(request,url.getRealUrl());
    }
}

