package com.jeequan.jeepay.member.ctrl.member;

import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.db.entity.MchAppEntity;
import com.jeequan.jeepay.db.entity.MemberRechargeRecord;
import com.jeequan.jeepay.db.entity.PayOrder;
import com.jeequan.jeepay.member.ctrl.CommonCtrl;
import com.jeequan.jeepay.service.impl.MchAppService;
import com.jeequan.jeepay.service.impl.MemberRechargeRecordService;
import com.jeequan.jeepay.util.JeepayKit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/*
* 会员充值 - 回调函数
*
* @author zx
* @date 2023/4/12 14:22
*/
@Slf4j
@RestController
@RequestMapping("/api/anon/notify")
public class MemberRechargeNotifyController extends CommonCtrl {

    @Autowired private MchAppService mchAppService;
    @Autowired private MemberRechargeRecordService memberRechargeRecordService;

    /** 会员充值 - 回调函数 */
    @RequestMapping("/memberRecharge")
    public String memberRechargeNotify() {

        String logPrefix = "===== 进入【商户会员充值回调】=====";

        //请求参数
        JSONObject params = getReqParamJSON();
        log.info("{}通知参数={}", logPrefix, params.toJSONString());

        // 充值记录
        String rechargeRecordId = getValString("mchOrderNo"); // 充值单号
        MemberRechargeRecord rechargeRecord = memberRechargeRecordService.getById(rechargeRecordId);
        if (rechargeRecord == null) {
            log.warn("{}充值记录不存在，充值记录ID={}", logPrefix, rechargeRecordId);
            return "memberRechargeRecord is not exists";
        }
        if (rechargeRecord.getState() == MemberRechargeRecord.STATE_SUCCESS || rechargeRecord.getState() == MemberRechargeRecord.STATE_FAIL) {
            log.info("{}充值记录状态已完结，状态={}, 充值记录ID={}", logPrefix, rechargeRecord.getState(), rechargeRecordId);
            return "success";
        }

        String mchNo = params.getString("mchNo");
        String appId = params.getString("appId");
        String sign = params.getString("sign");
        MchAppEntity mchAppEntity = mchAppService.getById(appId);
        if(mchAppEntity == null || !mchAppEntity.getMchNo().equals(mchNo)){
            log.warn("{}商户应用不存在，充值记录ID={}", logPrefix, rechargeRecordId);
            return "app is not exists";
        }

        // 验签
        params.remove("sign");
        if(!JeepayKit.getSign(params, mchAppEntity.getAppSecret()).equalsIgnoreCase(sign)){
            log.warn("{}验签失败，充值记录ID={}", logPrefix, rechargeRecordId);
            return "sign fail";
        }

        int payOrderState = params.getInteger("state"); // 支付订单状态 0-订单生成 1-支付中 2-支付成功 3-支付失败

        boolean updateOrderSuccess = true; //默认更新成功
        // 支付成功
        if (payOrderState == PayOrder.STATE_SUCCESS) {
            updateOrderSuccess = memberRechargeRecordService.updateIng2SuccessAndMbrAccount(rechargeRecordId, params.getString("payOrderId"));

        // 支付失败
        }else if (payOrderState == PayOrder.STATE_FAIL) {
            updateOrderSuccess = memberRechargeRecordService.updateIng2Fail(rechargeRecordId, params.getString("errCode"), params.getString("errMsg"));
        }
        // 更新订单 异常
        if(!updateOrderSuccess){
            log.error("{}，充值记录ID={}，updateOrderSuccess={} ", logPrefix, rechargeRecordId, updateOrderSuccess);
            return "fail";
        }

        log.info("===== {}, 通知完成。 充值记录ID={}, payOrderState={} =====", logPrefix, rechargeRecordId, payOrderState);
        return "success";
    }


}
