package com.ghy.payment.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ghy.common.adapay.model.AdapayStatusEnum;
import com.ghy.common.core.text.Convert;
import com.ghy.common.enums.PayStatus;
import com.ghy.common.enums.RefundType;
import com.ghy.payment.domain.FinancialChangeRecord;
import com.ghy.payment.mapper.FinancialChangeRecordMapper;
import com.ghy.payment.service.AdapayService;
import com.ghy.payment.service.FinancialChangeRecordService;
import com.huifu.adapay.core.exception.BaseAdaPayException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.RoundingMode;
import java.util.*;

/**
 * @author clunt
 */
@Slf4j
@Service
public class FinancialChangeRecordServiceImpl implements FinancialChangeRecordService {

    @Resource
    private AdapayService adapayService;
    @Resource
    private FinancialChangeRecordMapper financialChangeRecordMapper;

    @Override
    public FinancialChangeRecord selectNotPayRecordByDetailId(Long orderDetailId) {
        return financialChangeRecordMapper.selectNotPayRecordByDetailId(orderDetailId);
    }

    /**
     * 查询改价记录
     *
     * @param id 改价记录主键
     * @return 改价记录
     */
    @Override
    public FinancialChangeRecord selectFinancialChangeRecordById(Long id) {
        return financialChangeRecordMapper.selectFinancialChangeRecordById(id);
    }

    /**
     * 查询改价记录列表
     *
     * @param financialChangeRecord 改价记录
     * @return 改价记录
     */
    @Override
    public List<FinancialChangeRecord> selectFinancialChangeRecordList(FinancialChangeRecord financialChangeRecord) {
        return financialChangeRecordMapper.selectFinancialChangeRecordList(financialChangeRecord);
    }

    @Override
    public List<FinancialChangeRecord> selectByDetailIds(String ids) {
        if (StringUtils.isBlank(ids)) {
            return new ArrayList<>();
        }
        return financialChangeRecordMapper.selectByDetailIds(ids);
    }

    @Override
    public List<FinancialChangeRecord> selectByOrderDetailIds(Set<Long> orderDetailIds) {
        if (CollectionUtils.isEmpty(orderDetailIds)) {
            return new ArrayList<>();
        }
        StringJoiner joiner = new StringJoiner(",");
        orderDetailIds.forEach(x -> joiner.add(x.toString()));
        return financialChangeRecordMapper.selectByDetailIds(joiner.toString());
    }

    /**
     * 新增改价记录
     *
     * @param financialChangeRecord 改价记录
     * @return 结果
     */
    @Override
    public int insert(FinancialChangeRecord financialChangeRecord) {
        financialChangeRecord.setLeftMoney(financialChangeRecord.getChangeMoney());
        return financialChangeRecordMapper.insertFinancialChangeRecord(financialChangeRecord);
    }

    /**
     * 修改改价记录
     *
     * @param financialChangeRecord 改价记录
     * @return 结果
     */
    @Override
    public int update(FinancialChangeRecord financialChangeRecord) {
        return financialChangeRecordMapper.updateFinancialChangeRecord(financialChangeRecord);
    }

    /**
     * 批量删除改价记录
     *
     * @param ids 需要删除的改价记录主键
     * @return 结果
     */
    @Override
    public int deleteFinancialChangeRecordByIds(String ids) {
        return financialChangeRecordMapper.deleteFinancialChangeRecordByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除改价记录信息
     *
     * @param id 改价记录主键
     * @return 结果
     */
    @Override
    public int deleteFinancialChangeRecordById(Long id) {
        return financialChangeRecordMapper.deleteFinancialChangeRecordById(id);
    }

    @Override
    public List<FinancialChangeRecord> selectByMasterId(Long orderMasterId) {
        return financialChangeRecordMapper.selectByMasterId(orderMasterId);
    }

    @Override
    public List<FinancialChangeRecord> selectByMasterIds(Set<Long> orderMasterIds) {
        if (CollectionUtils.isEmpty(orderMasterIds)) {
            return new ArrayList<>();
        }
        return financialChangeRecordMapper.selectByMasterIds(orderMasterIds);
    }

    @Override
    public int updatePayStatus(Long id, Integer payStatus) {
        return financialChangeRecordMapper.updatePayStatus(id, payStatus);
    }

    @Override
    public boolean refund(Long deptId, Long id) {
        FinancialChangeRecord fcr = selectFinancialChangeRecordById(id);
        if (fcr == null) {
            return false;
        }
        FinancialChangeRecord update = new FinancialChangeRecord();
        update.setId(fcr.getId());
        update.setPayStatus(PayStatus.REFUNDING.getCode());
        update.setUpdateTime(new Date());
        update(update);
        String reverseAmt = fcr.getChangeMoney().setScale(2, RoundingMode.DOWN).toString();
        log.info("加价单[{}]退款: {}元", fcr.getId(), reverseAmt);
        JSONObject response;
        try {
            response = adapayService.payReverse(deptId, fcr.getPaymentId(), reverseAmt, RefundType.RCG);
        } catch (BaseAdaPayException e) {
            log.error("加价单退款失败: {}", e.getMessage(), e);
            return false;
        }
        boolean status = AdapayStatusEnum.succeeded.code.equals(response.getString("status")) ||
                AdapayStatusEnum.pending.code.equals(response.getString("status"));
        if (status) {
            // 发起撤销支付成功
            update.setId(fcr.getId());
            update.setReverseId(response.getString("id"));
            update(update);
        } else {
            log.error("改价单退款失败: {}", response.toJSONString());
        }
        return status;
    }

    @Override
    public void refundSucceeded(String reverseId) {
        financialChangeRecordMapper.refundSucceeded(reverseId);
    }

    @Override
    public int updatePay(Long id, String paymentId, Integer payStatus) {
        return financialChangeRecordMapper.updatePay(id, paymentId, payStatus);
    }
}
