package org.springblade.modules.auth.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springblade.core.secure.utils.WebUtil;
import org.springblade.core.tool.exception.ServiceException;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.auth.enums.UserEnum;
import org.springblade.modules.auth.utils.TokenUtil;
import org.springblade.modules.system.entity.Tenant;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.entity.UserInfo;
import org.springblade.modules.system.entity.VisualSubscribeNotifyConf;
import org.springblade.modules.system.enums.NotifyType;
import org.springblade.modules.system.service.ITenantService;
import org.springblade.modules.system.service.IUserService;
import org.springblade.modules.system.service.VisualSubscribeNotifyConfService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.spec.InvalidParameterSpecException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class BladeMicroAppTokenService {

    @Autowired
    private VisualSubscribeNotifyConfService visualSubscribeNotifyConfService;

    @Autowired
    private IUserService userService;

    @Autowired
    private ITenantService tenantService;

    public Map<String,String> wxRegistry(String encryptedData, String iv, String code) {
        Map<String,String> map = new HashMap<>();
        //第一步：通过code获取openid sessionKey
        JSONObject sessionKeyOrOpenId = getSessionKeyOrOpenId(code);

        String openid = sessionKeyOrOpenId.getStr("openid");
        String sessionKey = sessionKeyOrOpenId.getStr("session_key");
        String unionid = sessionKeyOrOpenId.getStr("unionid");

        //第二步：从encryptedData iv 解密 用户信息 拿到手机号
        JSONObject userInfo = getUserInfo(encryptedData, iv, sessionKey);

        String phone = userInfo.getStr("phoneNumber");
        map.put("openid",openid);
        map.put("unionid",unionid);
        map.put("phone",phone);
        return map;
    }

    public JSONObject getSessionKeyOrOpenId(String code){

        String appId = "";
        String secret = "";
        String requestUrl = "";
        List<VisualSubscribeNotifyConf> list = visualSubscribeNotifyConfService.list(Wrappers.<VisualSubscribeNotifyConf>lambdaQuery()
                .eq(VisualSubscribeNotifyConf::getNotifyType, NotifyType.microAppLogin.getValue()));
        for (VisualSubscribeNotifyConf notifyConf : list) {
            if ("app_id".equals(notifyConf.getAttriKey())){
                appId = notifyConf.getAttriValue();
            } else if ("app_secret".equals(notifyConf.getAttriKey())){
                secret = notifyConf.getAttriValue();
            } else if ("app_url".equals(notifyConf.getAttriKey())) {
                requestUrl = notifyConf.getAttriValue();
            }
        }

        Map<String, Object> requestUrlParam = new HashMap<>();
        requestUrlParam.put("appid", appId);//小程序appId
        requestUrlParam.put("secret", secret);//小程序 appSecret
        requestUrlParam.put("js_code", code);//小程序端返回的code
        requestUrlParam.put("grant_type", "authorization_code");//默认参数

        //发送post请求读取调用微信接口获取openid用户唯一标识
        //我用的hutool工具包的HttpUtil、JSONUtil,各位按需导入
        JSONObject SessionKeyOpenId = null;
        try {
            String result = HttpUtil.get(requestUrl, requestUrlParam);
            SessionKeyOpenId = JSONUtil.parseObj(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return SessionKeyOpenId;
    }


    public static JSONObject getUserInfo(String encryptedData, String iv, String sessionKey) {
        // 被加密的数据
        byte[] dataByte = cn.hutool.core.codec.Base64.decode(encryptedData);
        // 加密秘钥
        byte[] keyByte = cn.hutool.core.codec.Base64.decode(sessionKey);
        // 偏移量
        byte[] ivByte = cn.hutool.core.codec.Base64.decode(iv);
        try {
            // 如果密钥不足16位，那么就补足.
            int base = 16;
            keyByte = completToBase(keyByte, base);
            ivByte = completToBase(ivByte, base);

            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                System.out.println(result);
                return JSONUtil.parseObj(result);
            }
        } catch (NoSuchAlgorithmException e) {
            log.error(e.getMessage(), e);
        } catch (NoSuchPaddingException e) {
            log.error(e.getMessage(), e);
        } catch (InvalidParameterSpecException e) {
            log.error(e.getMessage(), e);
        } catch (IllegalBlockSizeException e) {
            log.error(e.getMessage(), e);
        } catch (BadPaddingException e) {
            log.error(e.getMessage(), e);
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage(), e);
        } catch (InvalidKeyException e) {
            log.error(e.getMessage(), e);
        } catch (InvalidAlgorithmParameterException e) {
            log.error(e.getMessage(), e);
        } catch (NoSuchProviderException e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    //补全数组位数
    public static byte[] completToBase(byte[] bytes, int base) {
        byte[] temp = new byte[]{};
        if (bytes.length % base != 0) {
            int groups = bytes.length / base + (bytes.length % base != 0 ? 1 : 0);
            temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(bytes, 0, temp, 0, bytes.length);
            return temp;
        } else {
            return bytes;
        }
    }

    public UserInfo grant(User user) {
        String tenantId = user.getTenantId();
        String username = user.getAccount();
        String password = user.getPassword();
        UserInfo userInfo = null;
        if (StrUtil.isNotBlank(username) && StrUtil.isNotBlank(password)) {
            // 获取租户信息
            Tenant tenant = tenantService.getByTenantId(tenantId);
            if (TokenUtil.judgeTenant(tenant)) {
                throw new ServiceException(TokenUtil.USER_HAS_NO_TENANT_PERMISSION);
            }

            // 根据不同用户类型调用对应的接口返回数据，用户可自行拓展
            // 获取用户类型
            String userType = Func.toStr(WebUtil.getRequest().getHeader(TokenUtil.USER_TYPE_HEADER_KEY), TokenUtil.DEFAULT_USER_TYPE);
            if (userType.equals(UserEnum.WEB.getName())) {
                userInfo = userService.userInfo(tenantId, username, password, UserEnum.WEB);
            } else if (userType.equals(UserEnum.APP.getName())) {
                userInfo = userService.userInfo(tenantId, username, password, UserEnum.APP);
            } else {
                userInfo = userService.userInfo(tenantId, username, password, UserEnum.OTHER);
            }
        }
        return userInfo;
    }
}
