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.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.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.List;

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 Boolean checkNotEmpty(Object... str) {
        for (Object s : str) {
            if (s instanceof String) {
                String value = (String) s;
                if (StringUtils.isEmpty(value)) {
                    return false;
                }
            } else if (s == null) {
                return false;
            }
        }
        return true;
    }

    public static Boolean checkDate(String dateStr, String dateFormat) {
        if (StringUtils.isEmpty(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.isEmpty(token)) {
            token = request.getParameter("token");
        }
        if (StringUtils.isEmpty(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.isEmpty(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) {
        String token = request.getHeader("x-token");
        if (StringUtils.isEmpty(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.isEmpty(row.get(i))) {
                return i;
            }
        }
        return null;
    }


}
