package com.jeequan.jeepay.mch.ctrl.division;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jeequan.jeepay.components.mq.model.PayOrderDivisionMQ;
import com.jeequan.jeepay.components.mq.vender.IMQSender;
import com.jeequan.jeepay.core.constants.ApiCodeEnum;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.db.entity.PayInterfaceDefine;
import com.jeequan.jeepay.db.entity.PayOrderDivisionRecord;
import com.jeequan.jeepay.db.entity.RefundOrder;
import com.jeequan.jeepay.mch.ctrl.CommonCtrl;
import com.jeequan.jeepay.service.impl.PayInterfaceDefineService;
import com.jeequan.jeepay.service.impl.PayOrderDivisionRecordService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 分账记录
 *
 * @author terrfly
 *
 * @date 2021-08-25 11:50
 */
@RestController
@RequestMapping("api/division/records")
public class PayOrderDivisionRecordController extends CommonCtrl {

	@Autowired private PayOrderDivisionRecordService payOrderDivisionRecordService;
	@Autowired private IMQSender mqSender;
	@Autowired private PayInterfaceDefineService payInterfaceDefineService;

	/** list */
	@PreAuthorize("hasAnyAuthority( 'ENT_DIVISION_RECORD_LIST' )")
	@RequestMapping(value="", method = RequestMethod.GET)
	public ApiRes list() {

		PayOrderDivisionRecord queryObject = getObject(PayOrderDivisionRecord.class);
		queryObject.setMchNo(getCurrentMchNo());
		IPage<PayOrderDivisionRecord> pages = payOrderDivisionRecordService.listByPage(getIPage(true), queryObject);
		Map<String, String> ifCodeMap = new HashMap<>();
		List<PayInterfaceDefine> list = payInterfaceDefineService.list();
		if(!list.isEmpty()){
			for (PayInterfaceDefine define:list) {
				ifCodeMap.put(define.getIfCode(), define.getIfName());
			}
		}
		for (PayOrderDivisionRecord order:pages.getRecords()) {
			if(StringUtils.isNotBlank(order.getIfCode())){
				order.setIfName(ifCodeMap.get(order.getIfCode()));
			}
		}
		return ApiRes.page(pages);
	}

	/** detail */
	@PreAuthorize("hasAuthority( 'ENT_DIVISION_RECORD_VIEW' )")
	@RequestMapping(value="/{recordId}", method = RequestMethod.GET)
	public ApiRes detail(@PathVariable("recordId") Long recordId) {
		PayOrderDivisionRecord record = payOrderDivisionRecordService
				.getOne(PayOrderDivisionRecord.gw()
						.eq(PayOrderDivisionRecord::getMchNo, getCurrentMchNo())
						.eq(PayOrderDivisionRecord::getRecordId, recordId));
		if (record == null) {
            throw new BizException(ApiCodeEnum.SYS_OPERATION_FAIL_SEARCH);
        }
		return ApiRes.ok(record);
	}

	/** 分账接口重试 */
	@PreAuthorize("hasAuthority( 'ENT_DIVISION_RECORD_RESEND' )")
	@RequestMapping(value="/resend", method = RequestMethod.POST)
	public ApiRes resend() {
		List<String> recordIds = Arrays.asList(getValStringRequired("recordIds").split(","));

		// 筛选分账失败的账单
		List<PayOrderDivisionRecord> recordList = payOrderDivisionRecordService.list(
				PayOrderDivisionRecord.gw()
						.in(PayOrderDivisionRecord::getRecordId, recordIds)
						.eq(PayOrderDivisionRecord::getState, PayOrderDivisionRecord.STATE_FAIL)
		);
		if (CollUtil.isEmpty(recordList)) {
			throw new BizException(ApiCodeEnum.SYS_OPERATION_FAIL_SEARCH);
		}

		// 是否重新计算订单金额
		boolean isResendAndRecalAmount = (CS.YES == getValByteDefault("isResendAndRecalAmount", CS.NO));

		// 重发到MQ
		for (PayOrderDivisionRecord record: recordList) {
			mqSender.send(PayOrderDivisionMQ.build(record.getPayOrderId(), null, null, true, isResendAndRecalAmount));
		}

		return ApiRes.ok();
	}

}
