package com.jeequan.jeepay.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.utils.SeqKit;
import com.jeequan.jeepay.db.entity.PayOrder;
import com.jeequan.jeepay.db.entity.PayOrderDivisionRecord;
import com.jeequan.jeepay.service.mapper.PayOrderDivisionRecordMapper;
import com.jeequan.jeepay.service.mapper.PayOrderMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 分账记录表 服务实现类
 * </p>
 *
 * @author [mybatis plus generator]
 * @since 2021-08-19
 */
@Service
public class PayOrderDivisionRecordService extends ServiceImpl<PayOrderDivisionRecordMapper, PayOrderDivisionRecord> {

    @Autowired private PayOrderMapper payOrderMapper;

    /** 更新分账记录为分账成功  ( 单条 )  将：  分账已受理（上游受理）  更新为： 其他状态    **/
    public void updateRecordSuccessOrFailBySingleItem(Long recordId, Byte state, String channelRespResult){

        PayOrderDivisionRecord updateRecord = new PayOrderDivisionRecord();
        updateRecord.setState(state);
        updateRecord.setChannelRespResult( state == PayOrderDivisionRecord.STATE_SUCCESS ? "" : channelRespResult); // 若明确成功，清空错误信息。
        update(updateRecord, PayOrderDivisionRecord.gw().eq(PayOrderDivisionRecord::getRecordId, recordId).eq(PayOrderDivisionRecord::getState, PayOrderDivisionRecord.STATE_ACCEPT));

    }

    /** 更新分账记录为分账成功**/
    public void updateRecordSuccessOrFail(List<PayOrderDivisionRecord> records, Byte state, String channelBatchOrderId, String channelRespResult){

        if(records == null || records.isEmpty()){
            return ;
        }

        List<Long> recordIds = new ArrayList<>();
        records.stream().forEach(r -> recordIds.add(r.getRecordId()));

        PayOrderDivisionRecord updateRecord = new PayOrderDivisionRecord();
        updateRecord.setState(state);
        updateRecord.setChannelBatchOrderId(channelBatchOrderId);
        updateRecord.setChannelRespResult(channelRespResult);
        update(updateRecord, PayOrderDivisionRecord.gw().in(PayOrderDivisionRecord::getRecordId, recordIds)
                .in(PayOrderDivisionRecord::getState, Arrays.asList(PayOrderDivisionRecord.STATE_WAIT, PayOrderDivisionRecord.STATE_ING)) ); // 分账处理中也可变更状态

    }


    /** 批量更新分账金额（用于重新计算逻辑）  要求有事务 **/
    @Transactional
    public void batchUpdateRecordDivisionAmount(List<PayOrderDivisionRecord> recordList){

        for (PayOrderDivisionRecord record : recordList) {
            PayOrderDivisionRecord updateRecord = new PayOrderDivisionRecord();
            updateRecord.setRecordId(record.getRecordId());
            updateRecord.setPayOrderDivisionAmount(record.getPayOrderDivisionAmount());
            updateRecord.setCalDivisionAmount(record.getCalDivisionAmount());
            this.updateById(updateRecord);
        }
    }



    public IPage<PayOrderDivisionRecord> listByPage(IPage iPage, PayOrderDivisionRecord queryObject) {

        LambdaQueryWrapper<PayOrderDivisionRecord> condition = PayOrderDivisionRecord.gw();
        if (StringUtils.isNotEmpty(queryObject.getMchNo())) {
            condition.eq(PayOrderDivisionRecord::getMchNo, queryObject.getMchNo());
        }

        if(queryObject.getReceiverId() != null){
            condition.eq(PayOrderDivisionRecord::getReceiverId, queryObject.getReceiverId());
        }

        if(queryObject.getReceiverGroupId() != null){
            condition.eq(PayOrderDivisionRecord::getReceiverGroupId, queryObject.getReceiverGroupId());
        }

        if(StringUtils.isNotEmpty(queryObject.getAppId())){
            condition.like(PayOrderDivisionRecord::getAppId, queryObject.getAppId());
        }

        if(queryObject.getState() != null){
            condition.eq(PayOrderDivisionRecord::getState, queryObject.getState());
        }

        if(StringUtils.isNotEmpty(queryObject.getPayOrderId())){
            condition.eq(PayOrderDivisionRecord::getPayOrderId, queryObject.getPayOrderId());
        }

        if(StringUtils.isNotEmpty(queryObject.getAccNo())){
            condition.eq(PayOrderDivisionRecord::getAccNo, queryObject.getAccNo());
        }

        if(StringUtils.isNotEmpty(queryObject.getIfCode())){
            condition.eq(PayOrderDivisionRecord::getIfCode, queryObject.getIfCode());
        }

        // 时间范围条件
        Date[] dateRange = queryObject.buildQueryDateRange();
        if (dateRange[0] != null) {
            condition.ge(PayOrderDivisionRecord::getCreatedAt, dateRange[0]);
        }
        if (dateRange[1] != null) {
            condition.le(PayOrderDivisionRecord::getCreatedAt, dateRange[1]);
        }

        condition.orderByDesc(PayOrderDivisionRecord::getCreatedAt); //时间倒序

       return page(iPage, condition);

    }


    /** 更新分账订单为： 等待分账中的状态  **/
    @Transactional
    public void updateResendState(String payOrderId){

        PayOrder updateRecord = new PayOrder();
        updateRecord.setDivisionState(PayOrder.DIVISION_STATE_WAIT_TASK);

        // 更新订单
        int payOrderUpdateRow = payOrderMapper.update(updateRecord, PayOrder.gw()
                .eq(PayOrder::getPayOrderId, payOrderId)
                .in(PayOrder::getDivisionState, Arrays.asList(PayOrder.DIVISION_STATE_FINISH, PayOrder.DIVISION_STATE_ING)));

        if(payOrderUpdateRow <= 0){
            throw new BizException("更新订单分账状态失败");
        }

        PayOrderDivisionRecord updateRecordByDiv = new PayOrderDivisionRecord();
        updateRecordByDiv.setBatchOrderId(SeqKit.genDivisionBatchId()); // 重新生成batchOrderId, 避免部分失败导致： out_trade_no重复。
        updateRecordByDiv.setState(PayOrderDivisionRecord.STATE_WAIT); //待分账
        updateRecordByDiv.setChannelRespResult("");
        updateRecordByDiv.setChannelBatchOrderId("");
        boolean recordUpdateFlag = update(updateRecordByDiv,
                PayOrderDivisionRecord.gw().eq(PayOrderDivisionRecord::getPayOrderId, payOrderId).eq(PayOrderDivisionRecord::getState, PayOrderDivisionRecord.STATE_FAIL)
        );

        //当分账状态为： 分账处理中 时： 此时将更新失败， 无需更新即可。  删除抛异常逻辑。  // 20220510更新
        if(!recordUpdateFlag){
        }
    }


}
