package com.fs.qw.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fs.qw.domain.QwCompany;
import com.fs.qw.dto.ReceiptDto;
import com.fs.qw.service.IQwCompanyService;
import com.fs.qwApi.service.QwApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * 企业微信对外收款服务（调用获取收款记录接口）
 */
@Slf4j
@Service
public class WeWorkExternalPayService {

    @Autowired
    private QwApiService qwApiService;

    @Autowired
    private IQwCompanyService iQwCompanyService;


    /**
     * 拉取所有收款记录（自动分页）
     * @param beginTime 开始时间戳（秒）
     * @param endTime   结束时间戳（秒）
     * @param payeeUserid 可选，收款成员userid
     */
    public List<ReceiptDto> fetchAllReceipts(Long beginTime, Long endTime, String payeeUserid,String corpId) {
        QwCompany qwCompany = iQwCompanyService.selectQwCompanyByCorpId(corpId);
        String openSecret = qwCompany.getOpenSecret();
        if (StringUtils.isEmpty(openSecret)) {
            log.error("企业:{}未配置openSecret,跳过拉取收款记录",qwCompany.getCorpName());
            return Collections.emptyList();
        }

        List<ReceiptDto> allReceipts = new ArrayList<>();
        String cursor = null;

        do {
            Map<String, Object> params = new HashMap<>();
            params.put("begin_time", beginTime);
            params.put("end_time", endTime);
            if (StringUtils.hasText(payeeUserid)) {
                params.put("payee_userid", payeeUserid);
            }
            if (StringUtils.hasText(cursor)) {
                params.put("cursor", cursor);
            }
            params.put("limit", 1000);

            String accessToken = qwApiService.getToken(corpId, openSecret);
            String url = "https://qyapi.weixin.qq.com/cgi-bin/externalpay/get_bill_list?access_token=" + accessToken;

            // 发送 POST 请求
            String body = HttpUtil.post(url, JSONUtil.toJsonStr(params));
            JSONObject json = JSONUtil.parseObj(body);

            Integer errcode = json.getInt("errcode");
            if (errcode == null || errcode != 0) {
                String errmsg = json.getStr("errmsg", "");
                throw new RuntimeException("调用企业微信对外收款接口失败：" + errmsg);
            }

            cursor = json.getStr("next_cursor");
            JSONArray billList = json.getJSONArray("bill_list");
            if (billList != null && !billList.isEmpty()) {
                for (Object obj : billList) {
                    JSONObject item = (JSONObject) obj;
                    // 只处理收款记录（bill_type=0），如果要处理退款记录，后续完善
                    Integer billType = item.getInt("bill_type");
                    if (billType != null && billType == 0) {
                        ReceiptDto dto = convertToReceiptDto(item);
                        allReceipts.add(dto);
                    }
                }
            }
        } while (StringUtils.hasText(cursor));

        log.info("同步收款记录完成，时间范围：{} ~ {}，共 {} 条", beginTime, endTime, allReceipts.size());
        return allReceipts;
    }

    /**
     * 转换 JSON 对象为 ReceiptDto
     */
    private ReceiptDto convertToReceiptDto(JSONObject item) {
        ReceiptDto dto = new ReceiptDto();
        dto.setTransactionId(item.getStr("transaction_id"));
        dto.setBillType(item.getInt("bill_type"));
        dto.setTradeState(item.getInt("trade_state"));
        dto.setPayTime(item.getLong("pay_time"));
        dto.setOutTradeNo(item.getStr("out_trade_no"));
        dto.setExternalUserid(item.getStr("external_userid"));
        dto.setTotalFee(item.getInt("total_fee"));
        dto.setPayeeUserid(item.getStr("payee_userid"));
        dto.setPaymentType(item.getInt("payment_type"));
        dto.setMchId(item.getStr("mch_id"));
        dto.setRemark(item.getStr("remark"));
        dto.setTotalRefundFee(item.getInt("total_refund_fee"));

        // 嵌套对象（仅收款记录有）
        Object commodityListObj = item.get("commodity_list");
        if (commodityListObj != null) dto.setCommodityList(JSONUtil.toJsonStr(commodityListObj));
        Object contactInfoObj = item.get("contact_info");
        if (contactInfoObj != null) dto.setContactInfo(JSONUtil.toJsonStr(contactInfoObj));
        Object miniprogramInfoObj = item.get("miniprogram_info");
        if (miniprogramInfoObj != null) dto.setMiniprogramInfo(JSONUtil.toJsonStr(miniprogramInfoObj));

        // 退款记录特有字段
        dto.setOutRefundNo(item.getStr("out_refund_no"));
        dto.setRefundUserid(item.getStr("refund_userid"));
        dto.setRefundComment(item.getStr("refund_comment"));
        dto.setRefundReqtime(item.getLong("refund_reqtime"));
        dto.setRefundStatus(item.getInt("refund_status"));
        dto.setRefundFee(item.getInt("refund_fee"));

        return dto;
    }
}