package com.winsun.controller;

import com.winsun.auth.core.annotion.Permission;
import com.winsun.auth.core.base.controller.BaseController;
import com.winsun.auth.core.common.model.ResponseData;
import com.winsun.auth.core.shiro.ShiroUser;
import com.winsun.constant.FilePath;
import com.winsun.interfaces.PermissionVerification;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.util.Base64;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.List;

/**
 *
 * @Date 2020/3/6 16:44
 * @Version 1.0
 */
@Slf4j
@RestController
public class ImgController extends BaseController {

    /**
     * 服务器访问路径
     */
    private static String pathPre = "/vdb/springboot/school_center/manager/";

    //menuname = "图片路径"  只支持jpeg 和 png
    @PermissionVerification(value = {"/school-center/userManager/PartnerManagement","/school-center/order/order","/school-center/schoolmanager/schoolmanagement","/school-center/productManagement/package","/school-center/uploadVerify/studentCardVerify"})
    @Permission(menuname = "图片查询", value =  "/images", method = RequestMethod.POST,produces ={MediaType.IMAGE_JPEG_VALUE,MediaType.IMAGE_PNG_VALUE})
    public String getbackground(String url) {
        ShiroUser shiroUser = getShiroUser();
        if (!shiroUser.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "超级管理员", "系统管理员","县分管理员（订单）","合伙人"))) {
            return "无数据权限";
        }
        if(StringUtils.isBlank(url)){
            return "";
        }
        System.out.println("url :"+url);
        url = url.replace("manager/ciop","");
        byte[] bytes=new byte[10];
        String  imgurl= pathPre + FilePath.BACKGROUNDIMG.getValue()+"/"+url;
        imgurl = imgurl.replace("//", "/");

        File file = new File(imgurl);
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);

            bytes = new byte[inputStream.available()];

            if (inputStream != null) {
                inputStream.read(bytes, 0, inputStream.available());
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error("图片下载失败",e.getMessage());
        }finally{
            if (inputStream != null) {
                try{
                    inputStream.close();
                }catch (Exception e){}
            }
        }
        String s = Base64.encodeBase64String(bytes);
        return s;
    }
}
