package com.gree.mall.manager.utils;


import com.gree.mall.manager.bean.admin.AdminWebsitBean;
import com.gree.mall.manager.commonmapper.WebsitMapper;
import com.gree.mall.manager.constant.DailyConstant;
import com.gree.mall.manager.plus.entity.AdminUser;
import com.gree.mall.manager.plus.service.AdminUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class CommonUtils {




    public static List<String> initList(List<String> list,int size){
        int listSize = list.size();
        if(listSize < size){
            for(int i = listSize;i < size;i++){
                list.add("");
            }
        }
        return list;
    }

    public static List<Object> initList2(List<Object> list,int size){
        int listSize = list.size();
        if(listSize < size){
            for(int i = listSize;i < size;i++){
                list.add("");
            }
        }
        return list;
    }

    public static String getStatusNameOfStudentExam(int status){
        if(status == 1){
            return "未完成";
        }else if(status == 2){
            return "已完成";
        }else if(status == 0){
            return "作废";
        }
        return "";
    }

    //(1.未考试 2.已及格,3.未及格)
    public static String getExamStatusNameOfStudentExam(int examStatus){
        if(examStatus == 1){
            return "未考试";
        }else if(examStatus == 2){
            return "已及格";
        }else{
            return "未及格";
        }
    }

    public static String getSourceName(int source){
        if(source == 1){
            return "后台新增";
        }else{
            return "线上报名";
        }
    }

    public static Boolean checkNotEmpty(Object... str){
        for(Object s : str){
            if(s instanceof String) {
                String value = (String)s;
                if (StringUtils.isBlank(value)) {
                    return false;
                }
            }else if(s == null) {
                return false;
            }
        }
        return true;
    }

    public static Boolean checkDate(String dateStr,String dateFormat){
        if(StringUtils.isBlank(dateStr)){
            return true;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        try{
            sdf.parse(dateStr);
        }catch(Exception e){
            return false;
        }
        return true;
    }

    public static String getFormatUrl(String url) {
        if (url.startsWith("http:")) {
            url = StringUtils.replace(url, "http", "https");
        }

        return url;
    }


    public static String getUserId(HttpServletRequest request){
        String token = getToken(request);
        if (StringUtils.isBlank(token)) {
            token = request.getParameter("token");
        }
        if (StringUtils.isBlank(token)) {
            token = request.getParameter("x-token");
        }
        if(StringUtils.isBlank(token)){
            return null;
        }
        try {
            String userId = JwtUtils.validateJWT(token).getClaims().getId();
            return userId;
        }catch(Exception e){
            return null;
        }
    }

    public static String getUsername(HttpServletRequest request){
        String token = getToken(request);
        if(StringUtils.isBlank(token)){
            return "";
        }
        try {
            return JwtUtils.validateJWT(token).getClaims().get("username").toString();
        }catch(Exception e){
            return "";
        }
    }

    public static String getUsername() {
        HttpServletRequest request = RequestContextHolder.getRequestAttributes() != null ? ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest() : null;
        return getUsername(request);
    }


    public static AdminWebsitBean getAdminUser(HttpServletRequest request){
        try {
            String userId = getUserId(request);
            AdminUserService adminUserService = ApplicationContextUtils.getBean(AdminUserService.class);
            AdminUser adminUser = adminUserService.lambdaQuery()
                    .eq(AdminUser::getAdminUserId,userId)
                    .one();
            if(adminUser == null){
                return null;
            }
            WebsitMapper websitMapper = ApplicationContextUtils.getBean(WebsitMapper.class);
            AdminWebsitBean adminWebsitBean = new AdminWebsitBean();
            BeanUtils.copyProperties(adminUser,adminWebsitBean);
            adminWebsitBean.setWeidsitIds(websitMapper.queryWebsitIds(adminWebsitBean.getAdminUserId()));
            return adminWebsitBean;
        }catch(Exception e){
            AdminWebsitBean adminWebsitBean = new AdminWebsitBean();
            adminWebsitBean.setType(1);
            return adminWebsitBean;
        }
    }

    public static String getNickName(HttpServletRequest request){
        try{
            String token = getToken(request);
            if(StringUtils.isBlank(token))
                return null;
            return JwtUtils.validateJWT(token).getClaims().getSubject();
        }catch(Exception e){
            return "";
        }
    }

    public static String getNickName() {
        HttpServletRequest request = RequestContextHolder.getRequestAttributes() != null ? ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest() : null;
        return getNickName(request);
    }

    /**
     * 获取token
     */
    public static String getToken(HttpServletRequest request){
        if(request == null){
            return "";
        }
        String token = request.getHeader("x-token");
        if (StringUtils.isBlank(token)) {
            token = request.getParameter("token");
        }
        return token;
    }

    /**
     * 获取性别code
     * @param gender
     * @return
     */
    public static String getGenderCode(String gender){
        if(org.apache.commons.lang3.StringUtils.equals(gender,"男")){
            return "1";
        }else if(org.apache.commons.lang3.StringUtils.equals(gender,"女")){
            return "2";
        }
        //未知
        return "0";
    }


    public static void downloadFile(String fileName, HttpServletResponse response) throws IOException {
        InputStream inputStream = CommonUtils.class.getResourceAsStream("/template/" + fileName);
        response.setContentType("Content-Type:application/octet-stream");
        response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
        OutputStream outputStream = response.getOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, len);
        }
        inputStream.close();
        outputStream.close();
    }


    /**
     * 检查下标对应的值不能为空
     * @param row
     * @param index
     * @return
     */
    public static Integer checkRowEmpty(List<String> row, int[] index){
        for(int i : index){
            if(StringUtils.isBlank(row.get(i))){
                return i;
            }
        }
        return null;
    }



    /**
     * 组装服务单修改记录的日志
     *
     * @return
     */
    public static String supplyLog(String title, Object oldValue, Object newValue) {
        if (oldValue instanceof String) {
            oldValue = oldValue == null ? "" : oldValue;
            newValue = newValue == null ? "" : newValue;
            if (!StringUtils.equals((String) oldValue, (String) newValue)) {
                return "【" + title + "】修改前：" + oldValue + ",修改后：" + newValue + "。";
            }
        }
        if (oldValue instanceof Integer) {
            oldValue = oldValue == null ? 0 : oldValue;
            newValue = newValue == null ? 0 : newValue;
            if (!((Integer) oldValue).equals((Integer) newValue)) {
                return "【" + title + "】修改前：" + oldValue + ",修改后：" + newValue + "。";
            }
        }

        if(oldValue instanceof Boolean){
            oldValue = oldValue == null ? false : oldValue;
            newValue = newValue == null ? false : newValue;

            String a = (Boolean) oldValue ? "是" : "否";
            String b = (Boolean) newValue ? "是" : "否";
            if (!a.equals(b)) {
                return "【" + title + "】修改前：" + a + ",修改后：" + b + "。";
            }
        }

        if(oldValue instanceof Date){
            long o = oldValue == null ? 0 : ((Date) oldValue).getTime();
            long n = newValue == null ? 0 : ((Date) newValue).getTime();
            if(o != n){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                return "【" + title + "】修改前：" + sdf.format(oldValue) + ",修改后：" + sdf.format(newValue) + "。";
            }
        }

        if(oldValue == null && newValue != null){
            oldValue = oldValue == null ? "" : oldValue;
            newValue = newValue == null ? "" : newValue;
            return "【" + title + "】修改前：" + oldValue + ",修改后：" + newValue + "。";

        }
        if(oldValue != null && newValue == null){
            oldValue = oldValue == null ? "" : oldValue;
            newValue = newValue == null ? "" : newValue;
            return "【" + title + "】修改前：" + oldValue + ",修改后：" + newValue + "。";
        }
        return "";
    }


    public static void downloadFile(String filePath, String filename,HttpServletResponse response) throws IOException {
        Boolean isOnLine = false;
        URL url = new URL(filePath);
        URLConnection conn = url.openConnection();
        InputStream inputStream = conn.getInputStream();

        response.reset();
        response.setContentType(conn.getContentType());
        if (isOnLine) {
// 在线打开方式 文件名应该编码成UTF-8
            response.setHeader("Content-Disposition", "inline; filename=" + URLEncoder.encode(filename, "UTF-8"));
        } else {
//纯下载方式 文件名应该编码成UTF-8
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
        }

        byte[] buffer = new byte[1024];
        int len;
        OutputStream outputStream = response.getOutputStream();
        while ((len = inputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, len);
        }
        inputStream.close();
    }

    /**
     * 打包下载
     */
    public static void writeZip(HttpServletResponse response,String title,List<Map<String,Object>> files){
        String fileName = "info.zip";
        response.setContentType("application/zip");
        response.setHeader("content-disposition", "attachment;filename=" + fileName);

        ZipOutputStream zos = null;
        BufferedInputStream bis = null;
        try{
            zos = new ZipOutputStream(response.getOutputStream());
            byte[] buf = new byte[8192];
            int len;
            for (int i = 0; i < files.size(); i++) {
                String fileUrl = files.get(i).get("fileUrl").toString();
                String name = files.get(i).get("fileName").toString();
                URL url = new URL(fileUrl);
                URLConnection conn = url.openConnection();
                InputStream inputStream = conn.getInputStream();
                ZipEntry ze = new ZipEntry(name);
                zos.putNextEntry(ze);
                bis = new BufferedInputStream(inputStream);
                while ((len = bis.read(buf)) > 0) {
                    zos.write(buf, 0, len);
                }
                zos.closeEntry();
            }
            zos.closeEntry();
        }catch(Exception ex){
            ex.printStackTrace();
        }finally {
            if(bis != null){
                try{
                    bis.close();
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
            if(zos != null){
                try{
                    zos.close();
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        }
    }

    public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
        Map<String, Object> map = new HashMap<String, Object>();
        Class<?> clazz = obj.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            Object value = field.get(obj);
            map.put(fieldName, value);
        }
        return map;
    }

    public static String getIssueStatus(Integer status){
        if(DailyConstant.ISSUE_STATUS_NOT.equals(status))
            return "未发放";
        if(DailyConstant.ISSUE_STATUS_SUCCESS.equals(status))
            return "已发放";
        if(DailyConstant.ISSUE_STATUS_BANK_DO.equals(status))
            return "银行受理中";
        return "";
    }

    public static String getDoStatus(Integer status){
        if(DailyConstant.DO_STATUS_HAS.equals(status))
            return "已执行";
        if(DailyConstant.DO_STATUS_NOT.equals(status))
            return "未执行";
        return "";
    }

    public static String getCurDateFileName(String name, String fileSuffix) {
        return name + DateUtils.formatDate1(new Date()) + "." + fileSuffix;
    }
}
