package cn.hanghui.outapi.platform.alipay.service.impl;

import cn.hanghui.outapi.platform.alipay.api.AlipayCommonApi;
import cn.hanghui.outapi.platform.alipay.api.AlipayUserApi;
import cn.hanghui.outapi.platform.alipay.entity.dto.AlipayUserInfoExtInfoReqDto;
import cn.hanghui.outapi.platform.alipay.entity.dto.AlipayUserInfoReqDto;
import cn.hanghui.outapi.platform.alipay.entity.param.AlipayUserInfo;
import cn.hanghui.outapi.platform.alipay.service.AlipayFaceAuthService;
import cn.hanghui.outapi.platform.alipay.service.AlipayOpenApiService;
import cn.hanghui.outapi.platform.common.entity.rest.RestResult;
import cn.hanghui.outapi.platform.common.service.BaseService;
import cn.hanghui.outapi.platform.common.utils.Preconditions;
import cn.hanghui.outapi.platform.tenant.entity.dto.TenantVo;
import cn.hanghui.outapi.platform.tenant.service.TenantService;
import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
public class AlipayFaceAuthServiceImpl extends BaseService implements AlipayFaceAuthService {

    @Resource
    private AlipayUserApi alipayUserApi;

    @Resource
    private AlipayClient alipayFaceAuthClient;

    @Resource
    private AlipayClient alipayOpenApiClient5513;

    @Resource
    private AlipayCommonApi alipayCommonApi;

    @Autowired
    private TenantService tenantService;

    @Autowired
    private AlipayOpenApiService alipayOpenApiService;


    /**
     * 获取支付宝用户信息
     *
     * @param alipayUserInfoDto AlipayUserInfoDto
     * @return AlipayUserInfo
     */
    @Override
    public AlipayUserInfo getAlipayUserInfo(AlipayUserInfoReqDto alipayUserInfoDto) {
        /**---------------------------以下逻辑为新版本兼容老版本逻辑-------------------*/
        AlipayUserInfo userInfo = null;
        AlipayClient alipayClient = alipayFaceAuthClient;
        //根据sn获取三方授权商户信息（auth_token/auth_code）
        String thirdAppAuthToken = null;
        TenantVo tenant = tenantService.getThirdAppAuthTokenBySn(alipayUserInfoDto.getSn());
        if (tenant != null) {
            alipayClient = alipayOpenApiClient5513;
            thirdAppAuthToken = tenant.getAppAuthToken();
        }

        //兼容老版本
        if (alipayUserInfoDto.getAuthCode() != null && !"".equals(alipayUserInfoDto.getAuthCode().trim())) {
            userInfo = alipayUserApi.getUserInfo(alipayClient, alipayUserInfoDto.getAuthCode(), thirdAppAuthToken);
        }

        //封闭库 vid编码规则 IDENTITY_CARD + 机构编码 + 用户身份证
        if (userInfo == null
                && alipayUserInfoDto.getVid() != null
                && !"".equals(alipayUserInfoDto.getVid().trim())) {
            IsvInfo isvInfo = getIsvInfo(null);
            userInfo = alipayOpenApiService.getUserInfo(alipayUserInfoDto.getVid(), isvInfo.getOrgOutId());
        }

        //通用
        AlipayUserInfoExtInfoReqDto extInfoReqDto = handleExtInfo(alipayUserInfoDto.getExtInfo());
        if (userInfo == null
                && extInfoReqDto != null
                && extInfoReqDto.getAuthCode() != null
                && !"".equals(extInfoReqDto.getAuthCode().trim())) {
            //获取支付宝用户三要素+头像
            userInfo = alipayUserApi.getUserInfo(alipayClient, extInfoReqDto.getAuthCode(), thirdAppAuthToken);
        }

        //添加新逻辑 刷身份证
        if (userInfo == null
                && alipayUserInfoDto != null
                && alipayUserInfoDto.getCardnumber() != null
                && alipayUserInfoDto.getCardname() != null) {
            //刷身份证
            userInfo = new AlipayUserInfo();
            userInfo.setUserName(alipayUserInfoDto.getCardname());
            userInfo.setCertNo(alipayUserInfoDto.getCardnumber());
        }

        if (userInfo == null) {
            userInfo = new AlipayUserInfo();
        }

//        //获取现场刷脸照片 目前只有贵阳机场支持
//        if (alipayUserInfoDto.getFtoken() != null && !"".equals(alipayUserInfoDto.getFtoken().trim())) {
//            String photoBase64 = alipayUserApi.getPhotoBase64ByFtoken(alipayClient, alipayUserInfoDto.getFtoken(), "2", thirdAppAuthToken, alipayUserInfoDto.getAlipayUid());
//            userInfo.setPhotoBase64(photoBase64);
//        }
        log.info("--->获取支付宝用户信息响应参数:{}", JSONObject.toJSONString(userInfo));
        return userInfo;
    }


    @Override
    public void authIsvCallback(String appId, String appAuthCode) {
        try {
            //获取授权accessToken
            String accessToken = alipayCommonApi.getOpenAuthToken(alipayOpenApiClient5513, appAuthCode);
            if (accessToken == null) {
                return;
            }
            //根据appId更新accessToken
//            tenantService.updateAppAccessTokenByAppId(appId, accessToken);
        } catch (Exception e) {
            log.error("--->三方授权回调获取token服务异常", e);
        }

    }

    @Override
    public AlipayUserInfo getCommonAlipayUserInfo(AlipayUserInfoReqDto alipayUserInfoDto) {
        /**---------------------------以下逻辑为新版本兼容老版本逻辑-------------------*/
        AlipayUserInfo userInfo = null;
        String appId = null;

        if (alipayUserInfoDto.getAppId() != null
                && !"".equals(alipayUserInfoDto.getAppId().trim())) {
            appId = alipayUserInfoDto.getAppId();
        }

        if (Preconditions.isBlank(appId) && alipayUserInfoDto.getSn() != null && !"".equals(alipayUserInfoDto.getSn().trim())) {
            TenantVo tenantVo = tenantService.getBySn(alipayUserInfoDto.getSn());
            if (tenantVo != null) {
                appId = tenantVo.getServiceAppId();
            }
        }

        AlipayClient alipayClient = getAlipayClient(appId);
        //兼容老版本
        if (alipayUserInfoDto.getAuthCode() != null && !"".equals(alipayUserInfoDto.getAuthCode().trim())) {
            userInfo = alipayUserApi.getUserInfo(alipayClient, alipayUserInfoDto.getAuthCode(), null);
        }

        //封闭库 vid编码规则 IDENTITY_CARD + 机构编码 + 用户身份证
        if (userInfo == null
                && alipayUserInfoDto.getVid() != null
                && !"".equals(alipayUserInfoDto.getVid().trim())) {
            IsvInfo isvInfo = getIsvInfo(appId);
            userInfo = alipayOpenApiService.getUserInfo(alipayUserInfoDto.getVid(), isvInfo.getOrgOutId());
        }

        //通用
        AlipayUserInfoExtInfoReqDto extInfoReqDto = handleExtInfo(alipayUserInfoDto.getExtInfo());
        if (userInfo == null
                && extInfoReqDto != null
                && extInfoReqDto.getAuthCode() != null
                && !"".equals(extInfoReqDto.getAuthCode().trim())) {
            //获取支付宝用户三要素+头像
            userInfo = alipayUserApi.getUserInfo(alipayClient, extInfoReqDto.getAuthCode(), null);
        }

        //添加新逻辑 刷身份证
        if (userInfo == null
                && alipayUserInfoDto != null
                && alipayUserInfoDto.getCardnumber() != null
                && alipayUserInfoDto.getCardname() != null) {
            //刷身份证
            userInfo = new AlipayUserInfo();
            userInfo.setUserName(alipayUserInfoDto.getCardname());
            userInfo.setCertNo(alipayUserInfoDto.getCardnumber());
        }

        if (userInfo == null) {
            userInfo = new AlipayUserInfo();
        }

        //获取现场刷脸照片 目前只有贵阳机场/3138支持
        if (alipayUserInfoDto.getFtoken() != null && !"".equals(alipayUserInfoDto.getFtoken().trim()) && checkFtoken(appId)) {
            String photoBase64 = alipayUserApi.getPhotoBase64ByFtoken(alipayClient, alipayUserInfoDto.getFtoken(), "2", null, alipayUserInfoDto.getAlipayUid());
            userInfo.setPhotoBase64(photoBase64);
        }
        log.info("--->获取支付宝用户信息响应参数:{}", JSONObject.toJSONString(userInfo));
        return userInfo;
    }

    /**
     * 数据转换
     *
     * @param extInfo
     * @return
     */
    private AlipayUserInfoExtInfoReqDto handleExtInfo(Object extInfo) {
        AlipayUserInfoExtInfoReqDto dto = null;
        try {
            if (extInfo instanceof String) {
                dto = JSONObject.parseObject(String.valueOf(extInfo), AlipayUserInfoExtInfoReqDto.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("--->extInfo数据转换异常:{}", extInfo);

        }
        return dto;
    }

    @Override
    public AlipayUserInfo queryCommonUserInfo(AlipayUserInfoReqDto alipayUserInfoDto) {
        /**---------------------------以下逻辑为新版本兼容老版本逻辑-------------------*/
        AlipayUserInfo userInfo = null;
        String appId = null;

        if (alipayUserInfoDto.getAppId() != null
                && !"".equals(alipayUserInfoDto.getAppId().trim())) {
            appId = alipayUserInfoDto.getAppId();
        }

        if (Preconditions.isBlank(appId) && alipayUserInfoDto.getSn() != null && !"".equals(alipayUserInfoDto.getSn().trim())) {
            TenantVo tenantVo = tenantService.getBySn(alipayUserInfoDto.getSn());
            if (tenantVo != null) {
                appId = tenantVo.getServiceAppId();
            }
        }

        AlipayClient alipayClient = getAlipayClient(appId);
        //兼容老版本
        if (alipayUserInfoDto.getAuthCode() != null && !"".equals(alipayUserInfoDto.getAuthCode().trim())) {
            userInfo = alipayUserApi.getUserInfo(alipayClient, alipayUserInfoDto.getAuthCode(), null);
        }

        //封闭库 vid编码规则 IDENTITY_CARD + 机构编码 + 用户身份证
        if (userInfo == null
                && alipayUserInfoDto.getVid() != null
                && !"".equals(alipayUserInfoDto.getVid().trim())) {
            userInfo = alipayOpenApiService.getUserInfo(alipayUserInfoDto.getVid());
        }

        //通用
        AlipayUserInfoExtInfoReqDto extInfoReqDto = handleExtInfo(alipayUserInfoDto.getExtInfo());
        ;
        if (userInfo == null
                && extInfoReqDto != null
                && extInfoReqDto.getAuthCode() != null
                && !"".equals(extInfoReqDto.getAuthCode().trim())) {
            //获取支付宝用户三要素+头像
            userInfo = alipayUserApi.getUserInfo(alipayClient, extInfoReqDto.getAuthCode(), null);
        }

        //添加新逻辑 刷身份证
        if (userInfo == null
                && alipayUserInfoDto != null
                && alipayUserInfoDto.getCardnumber() != null
                && alipayUserInfoDto.getCardname() != null) {
            //刷身份证
            userInfo = new AlipayUserInfo();
            userInfo.setUserName(alipayUserInfoDto.getCardname());
            userInfo.setCertNo(alipayUserInfoDto.getCardnumber());
        }

        if (userInfo == null) {
            userInfo = new AlipayUserInfo();
        }

        //获取现场刷脸照片 目前只有贵阳机场支持
        if (alipayUserInfoDto.getFtoken() != null && !"".equals(alipayUserInfoDto.getFtoken().trim()) && checkFtoken(appId)) {
            String photoBase64 = alipayUserApi.getPhotoBase64ByFtoken(alipayClient, alipayUserInfoDto.getFtoken(), "2", null, alipayUserInfoDto.getAlipayUid());
            userInfo.setPhotoBase64(photoBase64);
        }
        log.info("--->获取支付宝用户信息响应参数:{}", JSONObject.toJSONString(userInfo));
        return userInfo;
    }


}
