package com.yonge.cooleshow.biz.dal.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.microsvc.toolkit.middleware.payment.common.api.BasePaymentService;
import com.microsvc.toolkit.middleware.payment.common.api.PaymentServiceContext;
import com.microsvc.toolkit.middleware.payment.common.api.entity.DivideReq;
import com.microsvc.toolkit.middleware.payment.common.api.entity.DivideResp;
import com.microsvc.toolkit.middleware.payment.common.api.enums.DivideBackStatus;
import com.yonge.cooleshow.biz.dal.entity.PaymentDivMemberRecord;
import com.yonge.cooleshow.biz.dal.service.*;
import com.yonge.cooleshow.biz.dal.wrapper.UserPaymentOrderWrapper;
import com.yonge.cooleshow.common.enums.EPayerType;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.beans.BeanUtils;
import lombok.extern.slf4j.Slf4j;
import com.yonge.cooleshow.biz.dal.entity.DivBackRecord;
import com.yonge.cooleshow.biz.dal.wrapper.DivBackRecordWrapper;
import com.yonge.cooleshow.biz.dal.mapper.DivBackRecordMapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 分账归还记录
 * 2023-10-18 10:59:05
 */
@Slf4j
@Service
public class DivBackRecordServiceImpl extends ServiceImpl<DivBackRecordMapper, DivBackRecord> implements DivBackRecordService {

    @Autowired
    private TenantMemberService tenantMemberService;

    @Autowired
    private PaymentServiceContext paymentServiceContext;

    @Autowired
    private PaymentDivMemberRecordService paymentDivMemberRecordService;

    @Autowired
    private UserPaymentOrderService userPaymentOrderService;

    @Autowired
    private UserPaymentCoreService userPaymentCoreService;

    /**
     * 查询详情
     * @param id 详情ID
     * @return DivBackRecord
     */
    @Override
    public DivBackRecord detail(Long id) {
        
        return baseMapper.selectById(id);
    }
    
    /**
     * 分页查询
     * @param page IPage<DivBackRecord>
     * @param query DivBackRecordWrapper.DivBackRecordQuery
     * @return IPage<DivBackRecord>
     */
    @Override
    public IPage<DivBackRecord> selectPage(IPage<DivBackRecord> page, DivBackRecordWrapper.DivBackRecordQuery query) {
        
        return page.setRecords(baseMapper.selectPage(page, query));
    }

    /**
     * 添加
     * @param divBackRecord DivBackRecordWrapper.DivBackRecord
     * @return Boolean
     */
    @Override
    public Boolean add(DivBackRecordWrapper.DivBackRecord divBackRecord) {

        return this.save(JSON.parseObject(divBackRecord.jsonString(), DivBackRecord.class));
    }

    /**
     * 更新
     * @param divBackRecord DivBackRecordWrapper.DivBackRecord
     * @return Boolean
     */
    @Override
    public Boolean update(DivBackRecordWrapper.DivBackRecord divBackRecord){

        return this.updateById(JSON.parseObject(divBackRecord.jsonString(), DivBackRecord.class));       
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void divBack() {
        // 查询分账回归在等待中的状态 ，遍历调用查询分账回归接口 回归成功的 修改回归状态，在调用退款接口
        List<DivBackRecord> list = this.lambdaQuery()
            .eq(DivBackRecord::getStatus, DivideBackStatus.PROCESSING.name())
            .list();

        for (DivBackRecord divBackRecord : list) {

            PaymentDivMemberRecord divMemberRecord = paymentDivMemberRecordService.getById(divBackRecord.getPaymentDivMemberRecordId());
            if (divMemberRecord == null){
                continue;
            }
            UserPaymentOrderWrapper.UserPaymentOrder paymentOrder = userPaymentOrderService
                .getUserPaymentOrderByOrderNo(divMemberRecord.getOrderNo());
            if (paymentOrder == null) {
                continue;
            }


            BasePaymentService paymentService = paymentServiceContext.getPaymentService(divBackRecord.getPaymentVendor());

            DivideReq.MemberDivideBack memberDivideBack = DivideReq.MemberDivideBack.builder()
                .payerName(EPayerType.YEEPAY.getDesc())
                .memberId(divMemberRecord.getMemberId())
                .platformPayeeMemberId(paymentService.getPaymentConfig().getMerchantId())
                .divideBackOrderNo(divBackRecord.getDivideBackOrderNo())
                .payOrderNo(paymentOrder.getOrderNo())
                .transNo(paymentOrder.getTransNo())
                .build();
            DivideResp.DivideBack divideBack;
            try {
                divideBack = paymentService.queryDivideBack(tenantMemberService.getMerchantConfig(divBackRecord.getPaymentVendor()), memberDivideBack);
                if (divideBack == null) {
                    continue;
                }
            } catch (Exception e) {
                log.error("分账回归查询异常", e);
                continue;
            }

            if (divideBack.getStatus() == DivideBackStatus.SUCCESS) {
                // 修改回归状态
                divBackRecord.setStatus(DivideBackStatus.SUCCESS.name());
                this.updateById(divBackRecord);
                // 调用退款接口
                userPaymentCoreService.refundOnly("退款",paymentOrder.getOrderNo());
            } else if (divideBack.getStatus() == DivideBackStatus.FAIL) {
                // 修改回归状态
                divBackRecord.setStatus(DivideBackStatus.FAIL.name());
                this.updateById(divBackRecord);
            }
        }

    }
}