package com.ruoyi.web.controller.system;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
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 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("/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));
    }
}
