package cn.com.countrygarden.bi.main.util;

import cn.com.countrygarden.bi.main.dto.extension.ExtensionBaseDTO;
import cn.com.countrygarden.bi.main.dto.extension.ExtensionReportDTO;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.service.AccessTokenService;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
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.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @ClassName ExtensionReportUtils
 * @Description   市场拓展 -> 外拓绑定 --> 工具类
 * @Author Sjiang
 * @Date 2019/1/15 11:51
 * @Version 1.0
 **/
public class ExtensionReportUtils {


    public static Boolean isBlank(Integer param){
        if (param == null){
            return false;
        }
        if (param.intValue() <= 0){
            return false;
        }
        return true;
    }





    /**
     *  以下为服务器端判断客户端浏览器类型的方法
     * @param request
     * @return
     */
    public static String getBrowser(HttpServletRequest request) {
        String UserAgent = request.getHeader("USER-AGENT").toLowerCase();
        if (UserAgent != null) {
            if (UserAgent.indexOf("msie") != -1)
                return "IE";
            if (UserAgent.indexOf("firefox") != -1)
                return "FF";
            if (UserAgent.indexOf("safari") != -1)
                return "SF";
        }
        return null;
    }




    public static void responseDown(String fileName, XSSFWorkbook workbook,HttpServletResponse response,  HttpServletRequest request){
        /** 下载时文件名为中文：乱码解决 */
        // 响应的过程：
        // 服务器： utf-8|gbk --> iso8859-1    浏览器: iso8859-1 --> utf-8|gbk (firefox、chrome)
        // 服务器： gbk --> iso8859-1    浏览器: iso8859-1 --> gbk (msie)
        try {
            if ("FF".equals(getBrowser(request))) {
                // 针对火狐浏览器处理方式不一样了
                fileName = new String(fileName.getBytes("GB2312"), "ISO-8859-1");
            }else{
                //encode解决中文乱码
                fileName = URLEncoder.encode(fileName, "UTF-8");
            }
            /* 设置下载的文件名 */
            response.setHeader("content-disposition", "attachment;filename=" + fileName + ".xlsx");
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            /* 向浏览器输出Excel文件 */
            ServletOutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            /* 关闭工作簿 */
            workbook.close();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    /**
     * 该方法是用于相同对象不同属性值的合并，如果两个相同对象中同一属性都有值，那么sourceBean中的值会覆盖tagetBean重点的值
     * @param sourceBean    被提取的对象bean
     * @param targetBean    用于合并的对象bean
     * @return targetBean,合并后的对象
     */
    public static ExtensionReportDTO combineSydwCore(ExtensionReportDTO sourceBean, ExtensionReportDTO targetBean){
        Class sourceBeanClass = sourceBean.getClass();
        Class targetBeanClass = targetBean.getClass();

        Field[] sourceFields = sourceBeanClass.getDeclaredFields();
        Field[] targetFields = targetBeanClass.getDeclaredFields();
        for(int i=0; i<sourceFields.length; i++){
            Field sourceField = sourceFields[i];
            if (Modifier.isStatic(sourceField.getModifiers())){
                continue;
            }
            Field targetField = targetFields[i];
            if (Modifier.isStatic(targetField.getModifiers())){
                continue;
            }
            sourceField.setAccessible(true);
            targetField.setAccessible(true);
            try {
                if( !(sourceField.get(sourceBean) == null) &&  !"serialVersionUID".equals(sourceField.getName().toString())){
                    targetField.set(targetBean,sourceField.get(sourceBean));
                }
            } catch (IllegalArgumentException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return targetBean;
    }

    /**
     * @Author Sjiang
     * @Description  外拓绑定文件上传
     * @Date 14:32 2019/1/23
     * @Param [multipartFile, token]
     * @return void
     **/

    public static Map<String, String> uploadFile(MultipartFile multipartFile, OSSUtils ossUtils) {
        String interim = multipartFile.getOriginalFilename();
        String suffix = interim.substring(interim.lastIndexOf("."),interim.length());
        String fileRealName = UUID.randomUUID().toString().replaceAll("-", "")+suffix;
        try {
            HashMap<String, String> resultMap = Maps.newHashMap();
            resultMap.put("fileUrl",ossUtils.uploadFile(fileRealName, multipartFile.getInputStream()));
            resultMap.put("fileRealName",fileRealName);
            return resultMap;
        } catch (IOException e) {
            e.printStackTrace();
            throw new ServiceException("文件上传失败，请稍后重试！");
        }
    }

    /**
     * @Author sjiang
     * @Description   获取 userCode
     * @Date 14:25 2019-03-01
     * @Param [request]
     * @return java.lang.String
     **/
    public static String getUserCode(AccessTokenService accessTokenService, HttpServletRequest request){
        String accessToken = request.getParameter("AccessToken");
        if (accessToken != null){
            AccessToken token = accessTokenService.findByToken(accessToken);
            if (token != null){
                return token.getUserCode();
            }
        }
        throw new ServiceException("AccessToken 失效！");
    }


    /**
     * @Author Sjiang
     * @Description // 检查参数合法性
     * @Date 11:23 2019/1/17
     * @Param [d, pageRowBounds]
     * @return java.util.List<T>
     **/
    public static<D extends ExtensionBaseDTO> void checkBindingIdentifier(D dto){
        if (StringUtils.isBlank(dto.getBindingIdentifier())){
            throw new ServiceException("请传入查询标识 bindingIdentifier !");
        }
    }

}
