package com.ywt.alipaympapi.service;

import com.ptc.board.citymsg.sdk.UserAccountApi;
import com.ptc.board.citymsg.sdk.response.UserAccountInfo;
import com.ywt.alipaympapi.models.Constants;
import com.ywt.alipaympapi.models.auth.AlipayMpCfg;
import com.ywt.alipaympapi.models.auth.GetAlipayUserInfoReq;
import com.ywt.alipaympapi.models.auth.GetAlipayUserInfoResp;
import com.ywt.alipaympapi.models.enums.TerminalEnum;
import com.ywt.core.exception.AppMessageException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author Walker
 * Created on 2022/9/1
 */
@Slf4j
@Service
public class AuthService {

    /**
     * 换取支付宝用户信息
     */
    public GetAlipayUserInfoResp getAlipayUserInfo(GetAlipayUserInfoReq req) throws AppMessageException {
        GetAlipayUserInfoResp resp = new GetAlipayUserInfoResp();
        try {
            UserAccountApi api = new UserAccountApi("https", "ab-saas-api.alipay-eco.com", null, req.getSaasSecurityKey());
            UserAccountInfo userAccountInfo = api.queryUserInfo(req.getAppId(), req.getTicket());
            resp.setAlipayUid(userAccountInfo.getAlipayUid());
            resp.setAvatar(userAccountInfo.getAvatar());
            resp.setRealName(userAccountInfo.getFullName());
            resp.setNickName(userAccountInfo.getNickName());
            resp.setMobile(userAccountInfo.getPhone());
            resp.setAge(userAccountInfo.getAge());
            resp.setIdCardNo(userAccountInfo.getIdcardNo());
        } catch (Exception e) {
            log.error("AuthService#getAlipayUserInfo(req={} ):\n {}", req, e.getMessage(), e);
            throw new AppMessageException(e.getMessage());
        }
        return resp;
    }

    public AlipayMpCfg getCfg(int terminal) throws AppMessageException {
        AlipayMpCfg cfg = new AlipayMpCfg();
        if (TerminalEnum.valueOf(terminal) == TerminalEnum.NFYYBYFY_ALIPAY_MP) {
            // TODO: 后续多医院支持需要改成配置化
            cfg.setAppId(Constants.ALIPAYMP_APPID_NFYYBYFY);
            cfg.setSaasSecurityKey(Constants.ALIPAYMP_SAAS_SEC_KEY_NFYYBYFY);
            return cfg;
        }
        throw new AppMessageException(String.format("Unsupported terminal %d", terminal));
    }
}
