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

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jeequan.jeepay.core.entity.MchApplyment;
import com.jeequan.jeepay.core.entity.MchSubInfo;
import com.jeequan.jeepay.core.interfaces.paychannel.IIsvmchAlipayConfigService;
import com.jeequan.jeepay.core.model.applyment.ApplymentSignInfo;
import com.jeequan.jeepay.core.model.params.lklspay.LklspayIsvParams;
import com.jeequan.jeepay.core.utils.SpringBeansUtil;
import com.jeequan.jeepay.db.entity.MchSubInfoEntity;
import com.jeequan.jeepay.service.impl.MchSubInfoService;
import com.jeequan.jeepay.thirdparty.channel.lklspay.model.LklTkReqMethod;
import com.jeequan.jeepay.thirdparty.service.ConfigContextQueryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class LklspayIsvmchAlipayConfigService implements IIsvmchAlipayConfigService {

    @Autowired
    private MchSubInfoService mchSubInfoService;

    @Override
    public ApplymentSignInfo alipayOpenSignInfo(MchApplyment mchApplyment) {
        ApplymentSignInfo result = new ApplymentSignInfo();

        LambdaUpdateWrapper<MchSubInfoEntity> uWrapper = Wrappers.lambdaUpdate();

        // 获取到 服务商配置信息
        ConfigContextQueryService configContextQueryService = SpringBeansUtil.getBean(ConfigContextQueryService.class);
        LklspayIsvParams isvParams = (LklspayIsvParams) configContextQueryService.queryIsvParams(mchApplyment);

        JSONObject reqData = new JSONObject();
        String orderNo = DateUtil.format(new Date(), DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + RandomUtil.randomString(RandomUtil.BASE_NUMBER, 8);
        reqData.fluentPut("version", "1.0")
                .fluentPut("orderNo", orderNo)
                .fluentPut("orgCode", isvParams.getOrgCode())
                .fluentPut("merCupNo", mchApplyment.getChannelMchNo());

        JSONObject req = LklspayKit.openRequest(LklTkReqMethod.QUERY_SUB_MERC, isvParams, reqData);

        JSONArray subMercList = req.getJSONArray("list");
        List<Object> filteredMercList = subMercList.stream()
                .filter(t -> ((JSONObject) t).getString("registerChannel").equals("UNIONPAY"))
                .filter(t -> ((JSONObject) t).getString("registerType").equals("ZFBZF"))
                .collect(Collectors.toList());

        if (!filteredMercList.isEmpty()) {
            String subMchId = ((JSONObject) filteredMercList.get(0)).getString("subMchId");
            result.setChannelSubMchId(subMchId);
        }

        uWrapper.eq(MchSubInfoEntity::getChannelMchNo, mchApplyment.getChannelMchNo());
        uWrapper.eq(MchSubInfoEntity::getMchApplyId, mchApplyment.getApplyId());
        uWrapper.eq(MchSubInfoEntity::getSubMchType, "ZFB");

        // 微信开通意愿二维码地址
        result.setSignUrl(isvParams.getAliChannelExtUrl());
        result.setImgType(ApplymentSignInfo.IMG_TYPE_QRCONTENT);

        if (result.getChannelSubMchId() != null) {
            // 获取实名认证结果
            JSONObject reqData2 = new JSONObject();
            reqData2.fluentPut("merchantNo", mchApplyment.getChannelMchNo())
                    .fluentPut("tradeMode", "ALIPAY")
                    .fluentPut("subMerchantId", result.getChannelSubMchId());

            JSONObject respData = LklspayKit.openRequest(LklTkReqMethod.MCH_AUTH_STATUS, isvParams, reqData2);
            // 认证状态
            String authorizeState = respData.getString("checkResult");
            if ("AUTHORIZE_STATE_UNAUTHORIZED".equals(authorizeState)
                    || "UNAUTHORIZED".equals(authorizeState)) {
                uWrapper.set(MchSubInfoEntity::getAuthStatus, MchSubInfo.AUTH_STATUS_UNAUTHORIZED);
                result.setState("未授权");
            }

            if ("AUTHORIZE_STATE_AUTHORIZED".equals(authorizeState)
                    || "AUTHORIZED".equals(authorizeState)) {
                uWrapper.set(MchSubInfoEntity::getAuthStatus, MchSubInfo.AUTH_STATUS_AUTHORIZED);
                result.setState("已授权");
            }

            String rejectReason = respData.getString("rejectReason");

            uWrapper.set(MchSubInfoEntity::getRemark, rejectReason);
            uWrapper.eq(MchSubInfoEntity::getMchApplyId, mchApplyment.getApplyId());
            uWrapper.eq(MchSubInfoEntity::getMainUse, 1);

            mchSubInfoService.update(null, uWrapper);
        }


        return result;
    }
}
