package com.dtok.framework.base;


import cn.hutool.core.date.DateUtil;
import com.aliyun.oss.OSSClient;
import com.dtok.framework.exception.BizExceptionEnum;
import com.dtok.framework.exception.CoreExceptionEnum;
import com.dtok.framework.exception.ServiceException;
import com.dtok.framework.response.SuccessResponseData;
import com.dtok.framework.util.FileUtils;
import com.dtok.framework.util.HttpContext;
import com.dtok.framework.util.UploadUtils;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;

public class BaseController {
    protected static SuccessResponseData SUCCESS_TIP = new SuccessResponseData();

    protected HttpServletRequest getHttpServletRequest() {
        return HttpContext.getRequest();
    }

    protected HttpServletResponse getHttpServletResponse() {
        return HttpContext.getResponse();
    }

    protected HttpSession getSession() {
        return Objects.requireNonNull(HttpContext.getRequest()).getSession();
    }

    protected HttpSession getSession(Boolean flag) {
        return Objects.requireNonNull(HttpContext.getRequest()).getSession(flag);
    }

    protected String getPara(String name) {
        return Objects.requireNonNull(HttpContext.getRequest()).getParameter(name);
    }

    protected void setAttr(String name, Object value) {
        Objects.requireNonNull(HttpContext.getRequest()).setAttribute(name, value);
    }

    protected File saveFile(MultipartFile file) {
        String name = file.getOriginalFilename();
        String fileSavePath = UploadUtils.getExcelDirFile();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
        String str = sdf.format(new Date());
        File newFile = new File(fileSavePath + "/" + UUID.randomUUID() + "_" + str + name.substring(name.lastIndexOf(".")));
        try {
            file.transferTo(newFile);
        } catch (Exception e) {
            throw new ServiceException(BizExceptionEnum.UPLOAD_ERROR);
        }
        return newFile;
    }


    public String getObjectName(String dirPrefix, MultipartFile file) {
        // 文件后缀
        String suffixName = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."));
        String fileName = UUID.randomUUID() + suffixName;
        // 文件类型:1-图片，2-音频，3-视频
        String fileType = FileUtils.getFileType(suffixName);
        // 完整路径
        String objectName = "";
        switch (fileType) {
            case "1":
                objectName = dirPrefix + "images/" + DateUtil.today() + "/" + fileName;
                break;
            case "2":

                objectName = dirPrefix + "audio/" + DateUtil.today() + "/" + fileName;
                break;
            case "3":
                objectName = dirPrefix + "videos/" + DateUtil.today() + "/" + fileName;
                break;
            default:
                break;
        }
        return objectName;
    }


    protected File saveFile(MultipartFile file, String type) {
        String name = file.getOriginalFilename();
        String fileSavePath = UploadUtils.getExcelDirFile();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
        String str = sdf.format(new Date());
        File newFile = new File(fileSavePath + "/" + type + "/" + UUID.randomUUID() + "_" + str + name.substring(name.lastIndexOf(".")));
        if (!newFile.exists()) {
            newFile.mkdirs();
        }
        try {
            file.transferTo(newFile);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(BizExceptionEnum.UPLOAD_ERROR);
        }
        return newFile;
    }


    /**
     * 删除cookie
     */
    protected void deleteCookieByName(String cookieName) {
        Cookie[] cookies = this.getHttpServletRequest().getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(cookieName)) {
                Cookie temp = new Cookie(cookie.getName(), "");
                temp.setMaxAge(0);
                this.getHttpServletResponse().addCookie(temp);
            }
        }
    }

    /**
     * 删除所有cookie
     */
    protected void deleteAllCookie() {
        Cookie[] cookies = this.getHttpServletRequest().getCookies();
        for (Cookie cookie : cookies) {
            Cookie temp = new Cookie(cookie.getName(), "");
            temp.setMaxAge(0);
            this.getHttpServletResponse().addCookie(temp);
        }
    }

    /**
     * 返回前台文件流
     *
     * @author fengshuonan
     * @date 2017年2月28日 下午2:53:19
     */
    protected ResponseEntity<InputStreamResource> renderFile(String fileName, String filePath) {
        try {
            final FileInputStream inputStream = new FileInputStream(filePath);
            return renderFile(fileName, inputStream);
        } catch (FileNotFoundException e) {
            throw new ServiceException(CoreExceptionEnum.FILE_READING_ERROR);
        }
    }

    /**
     * 返回前台文件流
     *
     * @author fengshuonan
     * @date 2017年2月28日 下午2:53:19
     */
    protected ResponseEntity<InputStreamResource> renderFile(String fileName, byte[] fileBytes) {
        return renderFile(fileName, new ByteArrayInputStream(fileBytes));
    }

    /**
     * 返回前台文件流
     *
     * @param fileName    文件名
     * @param inputStream 输入流
     * @return
     * @author 0x0001
     */
    protected ResponseEntity<InputStreamResource> renderFile(String fileName, InputStream inputStream) {
        InputStreamResource resource = new InputStreamResource(inputStream);
        String dfileName = null;
        try {
            dfileName = new String(fileName.getBytes("gb2312"), "iso8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", dfileName);
        return new ResponseEntity<>(resource, headers, HttpStatus.CREATED);
    }
}
