package com.yonge.cooleshow.auth.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.dayaedu.cbs.openfeign.wrapper.qrcode.CbsQrCodeScanWrapper;
import com.yonge.cooleshow.auth.api.client.SysUserFeignService;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.auth.core.service.CustomTokenServices;
import com.yonge.cooleshow.auth.dal.dao.SysConfigDao;
import com.yonge.cooleshow.auth.service.SysUserService;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
import com.yonge.cooleshow.common.service.IdGeneratorService;
import com.yonge.toolset.base.exception.BizException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;

@Service
public class CbsQrCodeScanServiceImpl {

    @Resource
    private CustomTokenServices customTokenServices;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysUserFeignService sysUserFeignService;
    @Resource
    private SysConfigDao sysConfigDao;

    @Autowired
    private IdGeneratorService smsCodeService;

    public CbsQrCodeScanWrapper.UserInfo userInfo(CbsQrCodeScanWrapper.QrCodeScanUserInfoReq req) {
        CbsQrCodeScanWrapper.UserInfo userInfo = new CbsQrCodeScanWrapper.UserInfo();
        userInfo.setUsername(customTokenServices.loadAuthentication(req.getToken()).getName().split(":")[1]);
        userInfo.setClientTypes("TEACHER");

        SysUser sysUser = sysUserService.queryByPhone(userInfo.getUsername());
        if (sysUser == null) {
            throw new BizException(HttpStatus.UNAUTHORIZED.value(), "用户不存在");
        }
        // 查询老师机构ID
        Long tenantId = sysUserService.getTenantByClient(sysUser.getId(), "TEACHER");
        if (Objects.nonNull(tenantId) && tenantId == -1L) {
            // 平台老师不允许扫码登录乐教通，返回机构ID
            userInfo.setClientTypes("-1");
        }
        return userInfo;
    }

    public CbsQrCodeScanWrapper.QrCodeScanToken login(CbsQrCodeScanWrapper.QrCodeScanReq req) {
        //校验是否过期
        OAuth2Authentication auth2Authentication = customTokenServices.loadAuthentication(req.getPassword());
        String phone = auth2Authentication.getName().split(":")[1];
        SysUser sysUser = sysUserService.queryByPhone(phone);
        if (sysUser == null) {
            throw new BizException(HttpStatus.UNAUTHORIZED.value(), "用户不存在");
        }
        //获取需要排除的用户编号
        String excludeUserIds = sysConfigDao.findConfigValue("exclude_user_ids");
        if(StringUtils.isNotEmpty(excludeUserIds) && excludeUserIds.contains(sysUser.getId().toString())){
            throw new BizException("扫码登陆失败: 用户已锁定");
        }

        // 生成6位随机数验证码
        String code = RandomUtil.randomNumbers(6);
        // 保存验证码
        smsCodeService.saveVerifyValidCode(phone, code, "SMS_VERIFY_CODE_LOGIN");
        //调用登陆接口
        HttpResponseResult<Map<String,Object>> result = sysUserFeignService.smsLogin(phone, code,"SMS", req.getClientId(), req.getClientSecret());
        if (result != null){
            if(result.getCode() != 200){
                throw new BizException("扫码登陆失败", result.getMsg());
            }
            CbsQrCodeScanWrapper.QrCodeScanToken qrCodeScanToken = new CbsQrCodeScanWrapper.QrCodeScanToken();
            JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(result.getData().get("authentication")));
            qrCodeScanToken.setTokenData(jsonObject.getString("access_token"));
            return qrCodeScanToken;
        }
        throw new BizException("扫码登陆失败", "调用登陆接口失败");
    }
}
