package com.jeequan.jeepay.thirdparty.channel.kqpay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.entity.MchApplyment;
import com.jeequan.jeepay.core.entity.MchInfo;
import com.jeequan.jeepay.core.interfaces.paychannel.IIsvmchAlipayConfigService;
import com.jeequan.jeepay.core.model.applyment.ApplymentSignInfo;
import com.jeequan.jeepay.core.model.context.MchAppConfigContext;
import com.jeequan.jeepay.core.model.params.kqpay.KqpayIsvParams;
import com.jeequan.jeepay.core.utils.SpringBeansUtil;
import com.jeequan.jeepay.thirdparty.service.ConfigContextQueryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class KqpayIsvmchAlipayConfigService implements IIsvmchAlipayConfigService {
    @Override
    public ApplymentSignInfo alipayOpenSignInfo(MchApplyment mchApplyment) {
        ApplymentSignInfo result = new ApplymentSignInfo();

        // 进件商户信息
//        JSONObject suJson = JSON.parseObject(mchApplyment.getSuccResParameter());
//        if (suJson == null || StringUtils.isEmpty(suJson.getString("huifuId"))) {
//            result.setState("查询失败");
//            result.setErrInfo("商户参数为空，该商户还未进件成功");
//            return result;
//        }

        MchAppConfigContext mchAppConfigContext = new MchAppConfigContext();
        mchAppConfigContext.setMchType(MchInfo.TYPE_ISVSUB);
        mchAppConfigContext.setMchApplyment(mchApplyment);
        // 服务商配置参数
        ConfigContextQueryService configContextQueryService = SpringBeansUtil.getBean(ConfigContextQueryService.class);
        KqpayIsvParams isvParams = (KqpayIsvParams) configContextQueryService.queryIsvParams(mchApplyment.getIsvNo(), mchApplyment.getIfCode());
        // 渠道拓展地址
        result.setSignUrl(isvParams.getAliChannelExtUrl());
        // 图片类型
        result.setImgType(ApplymentSignInfo.IMG_TYPE_QRCONTENT);
        result.setState("当前通道无法确定认证状态");

        String succResParameter = mchApplyment.getSuccResParameter();
        JSONObject succRes = JSON.parseObject(succResParameter);
        JSONArray alipayList = succRes.getJSONArray("alipayList");
        if (alipayList.isEmpty()) {
            result.setState("未报备");
        } else {
            JSONObject aliReportData = alipayList.getJSONObject(0);
            String subMchId = aliReportData.getString("subMchId");
            if (ObjectUtils.isEmpty(subMchId)) {
                result.setChannelSubMchId(aliReportData.getString("errorMsg"));
            } else {
                result.setChannelSubMchId(subMchId);
            }
        }

        return result;
    }
}
