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

import com.jeequan.jeepay.converter.MchInfoConverter;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.db.entity.MchApplyment;
import com.jeequan.jeepay.mch.ctrl.CommonCtrl;
import com.jeequan.jeepay.service.impl.MchApplymentService;
import com.jeequan.jeepay.thirdparty.channel.kqpay.KqpayMchApplymentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("/api/mchApplyments")
public class KqpayMchApplymentController extends CommonCtrl {

    @Autowired
    private MchApplymentService mchApplymentService;

    @Autowired
    private KqpayMchApplymentService kqpayMchApplymentService;

    @Autowired
    private MchInfoConverter mchInfoConverter;

    @PostMapping("/kqSignApply/{recordId}")
    public ApiRes signApply(@PathVariable("recordId") String recordId) {
        MchApplyment dbRecord = mchApplymentService.getById(recordId);
        if (dbRecord == null || dbRecord.getState() != MchApplyment.STATE_WAIT_SIGN) {
            throw new BizException("请刷新当前申请单状态，该申请单当前状态无法执行该操作。");
        }

        com.jeequan.jeepay.core.entity.MchApplyment mchApplyment = kqpayMchApplymentService.signApply(mchInfoConverter.toModel(dbRecord));

        MchApplyment applymentResult = new MchApplyment();
        BeanUtils.copyProperties(mchApplyment, applymentResult);

        // 当状态发生了变化时
        if (!dbRecord.getState().equals(applymentResult.getState())) {

            // 更新数据
            applymentResult.setApplyId(recordId);
            applymentResult.setLastApplyAt(new Date());
            mchApplymentService.updateById(applymentResult);
        }
        return ApiRes.ok(applymentResult);
    }
}
