package shop.alien.job.store;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AntMerchantExpandIndirectZftorderQueryModel;
import com.alipay.api.request.AntMerchantExpandIndirectZftorderQueryRequest;
import com.alipay.api.response.AntMerchantExpandIndirectZftorderQueryResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import shop.alien.entity.store.AlipayZftCreateRecord;
import shop.alien.entity.store.StoreInfo;
import shop.alien.mapper.AlipayZftCreateRecordMapper;
import shop.alien.mapper.StoreInfoMapper;
import shop.alien.store.service.StoreInfoService;

import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
public class AlipayJob {

    private final AlipayZftCreateRecordMapper alipayZftCreateRecordMapper;

    private final StoreInfoMapper storeInfoMapper;

    /**
     * 查询支付宝二级商户进件结果，并从响应中回写门店 smid。
     */
    @XxlJob("getAlipayPartnerQuery")
    public void getAlipayPartnerQuery() throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());

        LambdaQueryWrapper<AlipayZftCreateRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AlipayZftCreateRecord::getInvokeSuccess, Boolean.TRUE);
        wrapper.isNotNull(AlipayZftCreateRecord::getOrderId);
        List<AlipayZftCreateRecord> records = alipayZftCreateRecordMapper.selectList(wrapper);

        for (AlipayZftCreateRecord record : records) {
            String orderId = record.getOrderId();
            if (StringUtils.isBlank(orderId)) {
                continue;
            }

            AntMerchantExpandIndirectZftorderQueryRequest request = new AntMerchantExpandIndirectZftorderQueryRequest();
            AntMerchantExpandIndirectZftorderQueryModel model = new AntMerchantExpandIndirectZftorderQueryModel();
            model.setOrderId(orderId.trim());
            request.setBizModel(model);

            AntMerchantExpandIndirectZftorderQueryResponse response = alipayClient.execute(request);
            if (response == null) {
                log.warn("order.query 返回为空 orderId={}", orderId);
                continue;
            }

            if (!response.isSuccess()) {
                log.warn("order.query 失败 orderId={} subMsg={}", orderId, response.getSubMsg());
                continue;
            }

            String body = response.getBody();
            String smid = extractSmidFromZftOrderQueryBody(body);
            if (StringUtils.isBlank(smid)) {
                log.debug("order.query 未解析到 smid orderId={}", orderId);
                continue;
            }

            Integer storeId = record.getStoreId();
            if (storeId == null) {
                log.debug("进件记录无 storeId，跳过回写 orderId={}", orderId);
                continue;
            }

            StoreInfo storeInfo = storeInfoMapper.selectById(storeId);
            if (storeInfo == null) {
                log.warn("门店不存在 storeId={} orderId={}", storeId, orderId);
                continue;
            }

            if (smid.equals(storeInfo.getAlipaySmid())) {
                continue;
            }

            storeInfo.setAlipaySmid(smid);
            storeInfoMapper.updateById(storeInfo);
            log.info("已回写门店 alipay_smid storeId={} orderId={}", storeId, orderId);
        }
    }

    /**
     * 从 ant.merchant.expand.indirect.zftorder.query 响应 body 中取 orders 首条的 smid。
     */
    private static String extractSmidFromZftOrderQueryBody(String body) {
        if (StringUtils.isBlank(body)) {
            return null;
        }
        try {
            JSONObject root = JSONObject.parseObject(body);
            JSONObject resp = root.getJSONObject("ant_merchant_expand_indirect_zftorder_query_response");
            if (resp == null) {
                return null;
            }
            JSONArray orders = resp.getJSONArray("orders");
            if (orders == null || orders.isEmpty()) {
                return null;
            }
            JSONObject first = orders.getJSONObject(0);
            return first == null ? null : first.getString("smid");
        } catch (Exception e) {
            log.warn("解析 zftorder.query 响应 body 失败: {}", e.getMessage());
            return null;
        }
    }

    private static AlipayConfig getAlipayConfig() {
        String privateKey  = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCBTOvScNrk0mw+WbR6Qtx2+HrPxB5IU/V2HSPGZUTDNiCiSU9UZcuXlo0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lbAy9PwxMi3CPHXsrHfZ+SnmzrOQQQUoErk40vnm9FiP74VwtWaD6llUZ25ohNeIi9yvHU5x/vAoGAdU2d1JOq85LHtsO+i9+8pyNnAsJ1YqTDtI5CtK2lqKvewswGIrlxOvi//AchVN3ExZmP0QDyfp31BhAs/T8iOl+Vqf7PzVjX+Eszch5aqwlzadmv3ZepnnamCGVE+hAsmkz0R6tebPjqYC7Ds/HbssQFLc4EyVBD5fwE5ZuR+OMCgYAvGHUYpi0dY9uMHXzL721tIopiwUfKCgLAn3yhSH3p7644NxHBqLLaBLVT2q7JAZQUaZUvXlwiyxU1zvo0xmvcbnB/Vd2qp8KbEUkvHyIYVJkM6Fn+9xBosorcrHv+7B2V1XR9WQcXvppxbN/8farWGuAA0anBD+UGrxd8B0/hHg==";
        String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnxevClLpYc6c8A9lwmnftPO2BeU+X6aZ/+b/n1Cvq096VJKiHmqcsRgRbrnSlmPDHRrQpDti4en2Ys0L2lx7CObIr/2xP/jJVwjIO1iWHUj/w/NAbjv7dLW/FFY4SeNp8rU+hlgGgviyUxzonfNfr3v+o8grFqQq27/hiZJAofsQRMQu1dEQqoKdJj7eQLkTstiK5miJMyQ+Y3tLztrEUMBz/zRgaCEfGqmFmRZ2diy2X+1dGaX6H4+0QJ2u50eY2QTBkNuvREGbAn6/lttAgvg/+CywPYKGeC4xOfnl5wP8iA1QXYbXrVJRkZjU097nyOmSNhLy9KvJH2BNpojS1QIDAQAB";
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl("https://openapi.alipay.com/gateway.do");
        alipayConfig.setAppId("2021005196608960");
        alipayConfig.setPrivateKey(privateKey);
        alipayConfig.setFormat("json");
        alipayConfig.setAlipayPublicKey(alipayPublicKey);
        alipayConfig.setCharset("UTF-8");
        alipayConfig.setSignType("RSA2");
        return alipayConfig;
    }
}
