package com.cico.nest.lcdp.boot.core.system.controller.admin.auth;

import com.alibaba.fastjson2.JSONObject;
import com.cico.nest.lcdp.boot.api.system.enums.logger.LoginLogTypeEnum;
import com.cico.nest.lcdp.boot.core.system.controller.admin.auth.vo.AuthLoginRespVO;
import com.cico.nest.lcdp.boot.core.system.dal.dataobject.user.AdminUserDO;
import com.cico.nest.lcdp.boot.core.system.service.auth.AdminAuthService;
import com.cico.nest.lcdp.boot.core.system.service.user.AdminUserService;
import com.cico.nest.lcdp.boot.core.system.util.CryptoUtil;
import com.cico.nest.lcdp.framework.common.pojo.CommonResult;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import static com.cico.nest.lcdp.boot.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static com.cico.nest.lcdp.framework.common.exception.enums.GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR;

/**
 * 系统间免密登录接口
 */
@RestController
@RequestMapping("/freelogin")
@Validated
@Slf4j
public class FreeLoginController {

    @Value("${qxsd.sdgk.freelogin-path}")
    private String freeLoginPath;

    @Value("${qxsd.sdgk.secretKey}")
    private String secretKey;
    @Value("${qxsd.sdgk.passwordDESKey}")
    private String passwordDESKey;

    @Resource
    private AdminUserService userService;
    @Resource
    private AdminAuthService authService;


    /**
     * 获取跳转到隧道管控的免密地址链接
     * @param mobile
     * @param id
     * @param link
     * @return
     */
    @GetMapping(value = "/sdgkFreePath")
    public CommonResult<String> freeLoginUrl(@RequestParam(value = "mobile", required = false) String mobile,
                                             @RequestParam(value = "id", required = false) String id,
                                             @RequestParam(value = "link", required = false) String link) {
        AdminUserDO user = null;
        if (StringUtils.isBlank(mobile)) {
            Long userId = getLoginUserId();
            user = userService.getUser(userId);
            if (user == null) {
                return CommonResult.error(INTERNAL_SERVER_ERROR.getCode(),"当前用户不存在");
            }
        }else {
            user = userService.getUserByMobile(mobile);
        }
        mobile = user.getMobile();
        if (StringUtils.isBlank(mobile)) {
            return CommonResult.error(INTERNAL_SERVER_ERROR.getCode(),"免登手机不存在");
        }
        //加密手机号
        String encryPhone = CryptoUtil.encrypt(mobile, passwordDESKey);
        //加密密钥
        String encrySecret = CryptoUtil.encrypt(secretKey, passwordDESKey);
        String url = String.format(freeLoginPath,encryPhone,encrySecret);
        if (StringUtils.isNotEmpty(id) ){
            url = url+"&id="+id;
        }
        if (StringUtils.isNotEmpty(link) ){
            url = url+"&link="+link;
        }
        return CommonResult.success(url);
    }

    /**
     * 免密登录
     */
    @GetMapping(value = "/login")
    public CommonResult<AuthLoginRespVO> freeThirdLogin(@RequestParam("mobile") String mobile) {
        CommonResult<AuthLoginRespVO> result = new CommonResult<>();
        try {
            //校验用户有效性
            String phone = CryptoUtil.decrypt(mobile, passwordDESKey);
            AdminUserDO sysUser = userService.getUserByMobile(phone);
            if (sysUser ==null) {
                log.error("免密登录入参的用户不存在");
                return CommonResult.error(INTERNAL_SERVER_ERROR.getCode(),"免密登录用户无效");
            }
            // 创建 Token 令牌，记录登录日志
            AuthLoginRespVO vo = authService.createTokenAfterLoginSuccess(sysUser.getId(),sysUser.getUsername(), LoginLogTypeEnum.LOGIN_MOBILE);
            result.setData(vo);
        } catch (Exception e) {
            log.error("免密登录异常", e);
            return CommonResult.error(INTERNAL_SERVER_ERROR.getCode(),"免密登录异常");
        }
        return result;
    }

}
