package com.fs.qw.service.impl;

import com.fs.qw.domain.FsCompanyExternalPayReceipt;
import com.fs.qw.domain.FsCompanyExternalPayRefund;
import com.fs.qw.domain.QwCompany;
import com.fs.qw.domain.QwUser;
import com.fs.qw.dto.ReceiptDto;
import com.fs.qw.mapper.FsCompanyExternalPayReceiptMapper;
import com.fs.qw.mapper.FsCompanyExternalPayRefundMapper;
import com.fs.qw.mapper.QwUserMapper;
import com.fs.qw.service.IFsCompanyExternalPayReceiptService;
import com.fs.qw.utils.MoneyUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;


import java.math.BigDecimal;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class FsCompanyExternalPayReceiptServiceImpl implements IFsCompanyExternalPayReceiptService {

    @Autowired
    private WeWorkExternalPayService weWorkPayService;

    @Autowired
    private FsCompanyExternalPayReceiptMapper receiptMapper;

    @Autowired
    private FsCompanyExternalPayRefundMapper refundMapper;

    @Autowired
    private QwUserMapper qwUserMapper;

    // 同步收、退款记录(定时任务同步或手动同步)
    @Override
    //移除 @Transactional，每个企业独立处理，一个失败不回滚其他企业
    public void syncReceipts(Long beginTime, Long endTime, String payeeUserid, List<QwCompany> qwCompanyList) {
        if (CollectionUtils.isEmpty(qwCompanyList)) {
            log.info("企业列表为空，无需同步");
            return;
        }

        for (QwCompany qwCompany : qwCompanyList) {
            String corpId = qwCompany.getCorpId();
            String corpName = qwCompany.getCorpName();
            try {
                List<ReceiptDto> receiptList = weWorkPayService.fetchAllReceipts(beginTime, endTime, payeeUserid, corpId);
                if (CollectionUtils.isEmpty(receiptList)) {
                    log.info("{}: 没有需要同步的记录", corpName);
                    continue;  // 重要：continue，不要 return
                }

                for (ReceiptDto dto : receiptList) {
                    if (dto.getBillType() == 0) {
                        // 收款记录
                        FsCompanyExternalPayReceipt entity = new FsCompanyExternalPayReceipt();
                        BeanUtils.copyProperties(dto, entity);
                        entity.setCorpId(corpId);        // 设置企业ID
                        entity.setCorpName(corpName);    // 设置企业名称
                        entity.setTotalFee(MoneyUtils.centToYuan(dto.getTotalFee()));
                        entity.setTotalRefundFee(MoneyUtils.centToYuan(dto.getTotalRefundFee()));
                        entity.setSaleTime(secondsToDate(dto.getPayTime()));//转成时间戳格式保存

                        //根据corpId和微信返回的user_id查询scrm系统中的companyUserId
                        QwUser qwUser = qwUserMapper.selectQwUserByCorpIdAndUserId(corpId, dto.getPayeeUserid());
                        if (qwUser!=null&&qwUser.getCompanyUserId()!=null){
                            entity.setCompanyUserId(qwUser.getCompanyUserId());
                        }
                        FsCompanyExternalPayReceipt exist = receiptMapper.selectByTransactionId(dto.getTransactionId());
                        if (exist == null) {
                            receiptMapper.insertFsCompanyExternalPayReceipt(entity);
                        } else {
                            entity.setId(exist.getId());
                            receiptMapper.updateFsCompanyExternalPayReceipt(entity);
                        }
                    } else if (dto.getBillType() == 1) {
                        // 退款记录
                        FsCompanyExternalPayRefund refund = new FsCompanyExternalPayRefund();
                        BeanUtils.copyProperties(dto, refund);
                        refund.setCorpId(corpId);
                        refund.setCorpName(corpName);
                        refund.setRefundFee(MoneyUtils.centToYuan(dto.getRefundFee()));
                        refund.setSaleTime(secondsToDate(dto.getPayTime()));//转成时间戳格式保存
                        //根据corpId和微信返回的user_id查询scrm系统中的companyUserId
                        QwUser qwUser = qwUserMapper.selectQwUserByCorpIdAndUserId(corpId, dto.getPayeeUserid());
                        if (qwUser!=null&&qwUser.getCompanyUserId()!=null){
                            refund.setCompanyUserId(qwUser.getCompanyUserId());
                        }
                        FsCompanyExternalPayRefund existRefund = refundMapper.selectByTransactionId(dto.getTransactionId());
                        if (existRefund == null) {
                            refundMapper.insertRefund(refund);
                        } else {
                            refund.setId(existRefund.getId());
                            refundMapper.updateRefund(refund);
                        }
                    }
                }
                log.info("{}: 同步完成，共处理 {} 条记录", corpName, receiptList.size());
            } catch (Exception e) {
                log.error("{}: 同步收款记录失败", corpName, e);
                // 继续处理下一个企业，不抛出异常
            }
        }
    }

    /**
     * 将秒数（从 1970-01-01 00:00:00 UTC 开始的秒数）转换为 Date 对象
     * @param seconds 秒数，例如 1780284515
     * @return Date 对象（对应的时间点为 seconds 秒后的时刻）
     */
    public static Date secondsToDate(long seconds) {
        // 秒转毫秒，直接构造 Date 对象
        return new Date(seconds * 1000L);
    }

    @Override
    public List<FsCompanyExternalPayReceipt> queryReceipts(FsCompanyExternalPayReceipt receipt) {
        List<FsCompanyExternalPayReceipt> fsCompanyExternalPayReceipts = receiptMapper.selectFsCompanyExternalPayReceiptList(receipt);
        if (CollectionUtils.isEmpty(fsCompanyExternalPayReceipts)){
            return Collections.emptyList();
        }
        return fsCompanyExternalPayReceipts;
    }

    @Override
    public List<FsCompanyExternalPayReceipt> selectFsCompanyExternalPayReceiptListByCompanyUserId(Long companyUserId) {
        FsCompanyExternalPayReceipt queryCondition=new FsCompanyExternalPayReceipt();
        queryCondition.setCompanyUserId(companyUserId);
        queryCondition.setStatus(BigDecimal.ZERO.intValue());//0:未使用
        List<FsCompanyExternalPayReceipt> fsCompanyExternalPayReceipts = receiptMapper.selectFsCompanyExternalPayReceiptList(queryCondition);
        if (org.apache.commons.collections4.CollectionUtils.isEmpty(fsCompanyExternalPayReceipts)){
            return Collections.emptyList();
        }
        return fsCompanyExternalPayReceipts;
    }
}