package com.jeequan.jeepay.mgr.ctrl.merchant;

import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.interfaces.IConfigContextQueryService;
import com.jeequan.jeepay.core.interfaces.paychannel.aliaqfbiz.IAliaqfApiService;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.core.model.DBApplicationConfig;
import com.jeequan.jeepay.core.model.params.aliaqf.AliaqfIsvParams;
import com.jeequan.jeepay.core.utils.SpringBeansUtil;
import com.jeequan.jeepay.db.entity.MchAppEntity;
import com.jeequan.jeepay.db.entity.MchInfo;
import com.jeequan.jeepay.db.entity.PayInterfaceConfig;
import com.jeequan.jeepay.db.entity.PayInterfaceDefine;
import com.jeequan.jeepay.mgr.ctrl.CommonCtrl;
import com.jeequan.jeepay.service.impl.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

/**
 * 商户支付接口管理类
 *
 * @author zhuxiao
 *
 * @date 2021-04-27 15:50
 */
@RestController
@RequestMapping("/api/mch/payConfigs")
public class MchPayInterfaceConfigController extends CommonCtrl {

    @Autowired private PayInterfaceConfigService payInterfaceConfigService;
    @Autowired private PayInterfaceDefineService payInterfaceDefineService;
    @Autowired private MchAppService mchAppService;
    @Autowired private MchInfoService mchInfoService;
    @Autowired private SysConfigService sysConfigService;
    @Autowired private IConfigContextQueryService configContextQueryService;


    /** 查询支付宝商户授权URL **/
    @GetMapping("/alipayIsvsubMchAuthUrls/{mchAppId}/{isvNo}")
    public ApiRes queryAlipayIsvsubMchAuthUrl(@PathVariable("mchAppId") String mchAppId, @PathVariable("isvNo") String isvNo) {

        MchAppEntity mchAppEntity = mchAppService.getById(mchAppId);
        DBApplicationConfig dbApplicationConfig = sysConfigService.getDBApplicationConfig();
        String authUrl = dbApplicationConfig.genAlipayIsvsubMchAuthUrl(isvNo, mchAppId);
        String authQrImgUrl = dbApplicationConfig.genScanImgUrl(authUrl);

        JSONObject result = new JSONObject();
        result.put("authUrl", authUrl);
        result.put("authQrImgUrl", authQrImgUrl);
        return ApiRes.ok(result);
    }

    /** 查询当前应用支持的支付接口
     *  使用功能：  新增分账用户
     * */
    @PreAuthorize("hasAuthority( 'ENT_DIVISION_RECEIVER_ADD' )")
    @RequestMapping(value="ifCodes/{appId}", method = RequestMethod.GET)
    public ApiRes getIfCodeByAppId(@PathVariable("appId") String appId) {

        if(mchAppService.lambdaQuery().eq(MchAppEntity::getAppId, appId).count() <= 0){
            throw new BizException("商户应用不存在");
        }

        Set<String> result = new HashSet<>();

        payInterfaceConfigService.list(PayInterfaceConfig.gw().select(PayInterfaceConfig::getIfCode)
                .eq(PayInterfaceConfig::getState, CS.PUB_USABLE)
                .eq(PayInterfaceConfig::getInfoId, appId)
                .eq(PayInterfaceConfig::getInfoType, CS.SYS_ROLE_TYPE.MCH_APP)
        ).stream().forEach(r -> result.add(r.getIfCode()));

        if(result.isEmpty()){
            return ApiRes.ok(new ArrayList<>());
        }

        return ApiRes.ok(payInterfaceDefineService.list(PayInterfaceDefine.gw()
                .select(PayInterfaceDefine::getIfCode, PayInterfaceDefine::getIfName, PayInterfaceDefine::getIcon, PayInterfaceDefine::getBgColor)
                .in(PayInterfaceDefine::getIfCode, result))
        );
    }

    /** 支付宝安全发签约页面 **/
    @GetMapping("/alipayAgreementPageSign/{mchAppId}/{isvNo}")
    public ApiRes alipayAgreementPageSign(@PathVariable("mchAppId") String mchAppId
            , @PathVariable("isvNo") String isvNo) {

        MchAppEntity mchAppEntity = mchAppService.getById(mchAppId);
        AliaqfIsvParams aliaqfIsvParams = applyCheck(mchAppEntity.getMchNo(), isvNo);

        IAliaqfApiService ALIAQFApiService = SpringBeansUtil.getBean(CS.IF_CODE.ALIAQF + "ApiService", IAliaqfApiService.class);

        // 1.获取签约页面
        String jumpUrl = ALIAQFApiService.userAgreementPageSign(aliaqfIsvParams, mchAppId);

        return ApiRes.ok(jumpUrl);
    }

    /** 查询支付宝安全发签约结果 **/
    @GetMapping("/queryUserAgreementPageSign/{mchAppId}/{isvNo}")
    public ApiRes queryUserAgreementPageSign(@PathVariable("mchAppId") String mchAppId
            , @PathVariable("isvNo") String isvNo) {

        MchAppEntity mchAppEntity = mchAppService.getById(mchAppId);
        AliaqfIsvParams ALIAQFIsvParams = applyCheck(mchAppEntity.getMchNo(), isvNo);

        IAliaqfApiService aliaqfApiService = SpringBeansUtil.getBean(CS.IF_CODE.ALIAQF + "ApiService", IAliaqfApiService.class);

        // 1.查询签约结果
        String agreementNo = aliaqfApiService.queryUserAgreementPageSign(ALIAQFIsvParams, mchAppId);

        String accountBookId = "";
        if (StringUtils.isNotEmpty(agreementNo)) {
            // 2.资金记账本开通
            accountBookId = aliaqfApiService.fundAccountbookCreate(ALIAQFIsvParams, mchAppId, mchAppEntity.getMchNo(), agreementNo);
        }

        JSONObject result = new JSONObject();
        result.put("agreementNo", agreementNo);
        result.put("accountBookId", accountBookId);

        return ApiRes.ok(result);
    }

    private AliaqfIsvParams applyCheck(String mchNo, String isvNo) {
        MchInfo mchInfo = mchInfoService.getById(mchNo);
        if (MchInfo.TYPE_ISVSUB != mchInfo.getType()) {
            throw new BizException("仅支持特约商户");
        }

        AliaqfIsvParams isvParams = (AliaqfIsvParams) configContextQueryService.queryIsvParams(isvNo, CS.IF_CODE.ALIAQF);
        if (isvParams == null) {
            throw new BizException("服务商未配置参数，请联系平台处理！");
        }
        return isvParams;
    }
}
