package com.ruoyi.web.controller.system;

import cn.hutool.json.JSONArray;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.util.CompreFace;
import com.alibaba.fastjson.parser.Feature;
import com.ruoyi.business.util.StringKit;
import com.ruoyi.cache.SmsCache;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.database.domain.dto.LoginDto;
import com.ruoyi.database.domain.dto.SMSLoginDto;
import com.ruoyi.database.domain.vo.SMSMsgVO;
import com.ruoyi.database.domain.vo.SmsVO;
import com.ruoyi.database.domain.vo.SwtMsgVO;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.service.ISysMenuService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@Api(tags = "登录验证")
@RestController
public class SysLoginController {
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ISysUserService sysUserService;


    private static final String PATH_PREFIX = "/home/dataaccess/facevideo/";
    private static final String USER_PATH_PREFIX = "/home/dataaccess/rwglUserFaceVideo/";
    // List of valid image extensions
    private static final List<String> IMAGE_EXTENSIONS = Arrays.asList("jpg", "jpeg", "png", "gif", "bmp");
    private static final String SMS_KEY = "SMS_KEY:";
    private static final String SWT_KEY = "SWT_KEY:";

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @ApiOperation("登录")
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    @ApiOperation("登录App")
    @PostMapping("/loginApp")
    public AjaxResult loginApp(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        loginBody.setCode("000000");
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }


    @ApiOperation("身份信息登录")
    @RequestMapping("/loginByName")
    public AjaxResult loginByCa(String name, String user) {
        try {
//            SysUser sysUser = sysUserService.selectUserByUserNum(user);
//            if (sysUser == null){
//                SysUser sysUser1 = new SysUser();
//                sysUser1.setUserName(user);
//                sysUser1.setPassword(user);
//                sysUser1.setNickName(name);
//                int i = sysUserService.insertUser(sysUser1);
//                if (i == 1){
//                    SysUser sysUser2 = sysUserService.selectUserByUserNum(user);
//                    Long[] longs = {6L};
//                    sysUserService.insertUserAuth(sysUser2.getUserId(),longs);
//                }
//            }
            AjaxResult ajax = AjaxResult.success();
            String token = loginService.loginAppBySms(name, user);
            JSONObject resJson = new JSONObject();
            resJson.put(Constants.TOKEN, token);
//            resJson.put("name", name);
            resJson.put("user", name);
            ajax.put(Constants.TOKEN, resJson);
            return ajax;
        } catch (Exception e) {
//            logger.info(StringKit.getTrace(e));
        }
        return AjaxResult.error("系统错误，请联系管理员");
    }


    @ApiOperation("人脸识别登录")
    @PostMapping("/loginByFace")
    public AjaxResult faceLogin(MultipartFile imgName) {
        try {
            if (imgName != null) {
                Path filePath = Paths.get(PATH_PREFIX, imgName.getOriginalFilename());
                File dest = new File(filePath.toString());
                // 确保目标目录存在
                Files.createDirectories(dest.getParentFile().toPath());
                // 保存文件到指定路径
                imgName.transferTo(dest);
                List<String> imageFiles = getImagesFromDirectory(USER_PATH_PREFIX);
                for (String imageFile : imageFiles) {
                    cn.hutool.json.JSONObject jsonObject = CompreFace.faceVerify(convertPngToBase64(imageFile), convertPngToBase64(PATH_PREFIX + dest.getName()));
                    if (jsonObject != null){
                        JSONArray face_matches = jsonObject.getJSONArray("face_matches");
                        System.out.println("图片中出现" + face_matches.size() + "张人脸");
                        for (int i = 0; i < face_matches.size(); i++) {
                            cn.hutool.json.JSONObject matchesJSONObject = face_matches.getJSONObject(i);
                            Double similarity = matchesJSONObject.getDouble("similarity");
                            System.out.println("人脸相似度：" + similarity);
                            if (similarity >= 0.98){
                                System.out.println("人脸识别通过");
                                String substring = imageFile.substring(imageFile.lastIndexOf("/") + 1, imageFile.lastIndexOf("."));
                                System.out.println("识别用户为" + substring);
                                AjaxResult ajax = AjaxResult.success();
                                String token = null;
                                try {
                                    token = loginService.loginAppBySms(substring, substring);
                                } catch (Exception e) {
                                    return AjaxResult.error("未检测到用户信息");
                                }
                                JSONObject resJson = new JSONObject();
                                resJson.put(Constants.TOKEN, token);
                                resJson.put("user", substring);
                                ajax.put(Constants.TOKEN, resJson);
                                return ajax;
                            }
                        }
                    }
                }
                System.out.println("人脸不匹配");
                return AjaxResult.error("人脸识别不通过，请靠近摄像头或拿掉面部遮挡物");
            } else {
                return AjaxResult.error("没图片");
            }
        } catch (Exception e) {
//            logger.info(StringKit.getTrace(e));
            return AjaxResult.error("系统错误，请联系管理员");
        }
    }

    @ApiOperation("短信验证码登录")
    @PostMapping("/loginBySMS")
    public AjaxResult loginBySMS(@RequestBody SMSLoginDto smsLoginDto) {
        try {
            RedisCache bean = SpringUtils.getBean(RedisCache.class);
            Integer type = smsLoginDto.getType();
            String code = smsLoginDto.getCode();
            String phone = smsLoginDto.getPhone();
            AjaxResult ajax = AjaxResult.success();
            if (type == 1) {
                SysUser sysUser = sysUserService.selectUserByUserName(phone);
                if (sysUser == null) {
                    return AjaxResult.error("用户不存在");
                }
                SwtMsgVO msgVO = bean.getCacheObject(SWT_KEY + phone);
                if (msgVO == null) {
                    return AjaxResult.error("苏网通消息发送出现异常，请稍后重试");
                }
                if (msgVO.getMsg().equals(code)) {
                    String token = loginService.loginAppBySms(sysUser.getUserName(), sysUser.getNickName());
                    JSONObject resJson = new JSONObject();
                    resJson.put(Constants.TOKEN, token);
                    resJson.put("user", sysUser.getUserName());
                    resJson.put("name", sysUser.getNickName());
                    ajax.put(Constants.TOKEN, resJson);
                    return ajax;
                }
                return AjaxResult.error("验证码错误，请重试");
            } else if (type == 2) {
                SysUser sysUser = sysUserService.selectUserByPhone(phone);
                if (sysUser == null) {
                    return AjaxResult.error("用户不存在");
                }
                SMSMsgVO msgVO = bean.getCacheObject(SMS_KEY + phone);
                if (msgVO == null) {
                    return AjaxResult.error("短信发送出现异常，请稍后重试");
                }
                if (msgVO.getMsg().equals(code)) {
                    String token = loginService.loginAppBySms(sysUser.getUserName(), sysUser.getNickName());
                    JSONObject resJson = new JSONObject();
                    resJson.put(Constants.TOKEN, token);
                    resJson.put("user", sysUser.getUserName());
                    resJson.put("name", sysUser.getNickName());
                    ajax.put(Constants.TOKEN, resJson);
                    return ajax;
                }
                return AjaxResult.error("验证码错误，请重试");
            } else {
                return AjaxResult.error("缺少type");
            }

        } catch (Exception e) {
//            logger.info(StringKit.getTrace(e));
        }
        return AjaxResult.error("系统错误，请联系管理员");
    }

    @ApiOperation("登录App-根据验证码")
    @PostMapping("/loginAppBySms")
    public AjaxResult loginAppBySms(@RequestBody LoginDto loginBody) {

        String smsStr = SmsCache.get(loginBody.getUsername());
        if ("".equals(StringKit.toString(smsStr))) {
            return AjaxResult.error("验证码不存在");
        }
        SmsVO smsVO = JSON.parseObject(smsStr, SmsVO.class, Feature.IgnoreNotMatch);
        //验证超时  30分钟
        Long nowTime = System.currentTimeMillis() / 1000;
        Long oldTime = smsVO.getTime();
        //30分钟有效
        if ((nowTime - oldTime) > 30 * 60) {
            return AjaxResult.error("验证码已失效，请重新发送");
        }
        //验证 验证码是否一致
        String nowCode = StringKit.toString(loginBody.getCode());
        String oldCode = StringKit.toString(smsVO.getMsg());
        if (!oldCode.equals(nowCode)) {
            return AjaxResult.error("验证码不匹配，请核实后输入");
        }
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.loginAppBySms(loginBody.getUsername(), loginBody.getCode());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }


    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser.getUserId();
        SysUser user = sysUserService.selectUserById(userId);
        String areaAuthCode = StringKit.toString(user.getAreaAuthCode());
        if (!"".equals(areaAuthCode)) {
            if (!"0".equals(areaAuthCode)) {
                String result = truncateAndPad(areaAuthCode);
                user.setAreaAuthCode(result);
            }
        }

        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    public static String truncateAndPad(String str) {
        if ("0".equals(StringKit.toString(str))) {
            return str;
        }
        // 去掉后面的所有的0
        String trimmed = str.replaceAll("0*$", "");
        // 如果少于4位，补0到4位
        if (trimmed.length() < 4) {
            trimmed = String.format("%-4s", trimmed).replace(' ', '0');
        }
        return trimmed;
    }


    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }


    public static List<String> getImagesFromDirectory(String directoryPath) {
        List<String> imageFiles = new ArrayList<>();
        File directory = new File(directoryPath);

        // Check if the specified path is a directory
        if (!directory.exists() || !directory.isDirectory()) {
            System.out.println("The specified path is not a directory or does not exist.");
            return imageFiles;
        }

        // Walk through the directory tree
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    // Recursively search subdirectories
                    imageFiles.addAll(getImagesFromDirectory(file.getAbsolutePath()));
                } else {
                    // Check if the file is an image based on its extension
                    String fileName = file.getName();
                    int dotIndex = fileName.lastIndexOf('.');
                    if (dotIndex != -1) {
                        String extension = fileName.substring(dotIndex + 1).toLowerCase();
                        if (IMAGE_EXTENSIONS.contains(extension)) {
                            imageFiles.add(file.getAbsolutePath());
                        }
                    }
                }
            }
        }

        return imageFiles;
    }

    public static String convertPngToBase64(String filePath) {
        File file = new File(filePath);

        // 检查文件是否存在
        if (!file.exists() || !file.isFile()) {
            System.out.println("File not found: " + filePath);
            return null;
        }

        // 读取文件为字节数组
        byte[] fileContent = null;
        try (FileInputStream fis = new FileInputStream(file)) {
            fileContent = new byte[(int) file.length()];
            int bytesRead = fis.read(fileContent);
            if (bytesRead != fileContent.length) {
                throw new IOException("Could not read the entire file to the byte array.");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        // 将字节数组转换为Base64字符串
        String base64String = Base64.getEncoder().encodeToString(fileContent);
        return base64String;
    }
}
