package com.jeequan.jeepay.core.model.openapi.biz.micro;

import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.exception.openapi.ParamException;
import com.jeequan.jeepay.core.model.openapi.AccessReq;
import com.jeequan.jeepay.core.model.rqrs.payorder.UnifiedOrderRQ;
import com.jeequan.jeepay.core.utils.JeepayKit;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

/**
 * TODO
 *
 * @author crystal
 * @date 2024/4/8 11:25
 */
@Data
public class MicroBizReq extends UnifiedOrderRQ {

   private String authCode;

   private String subAppid;

   /**
    * 参数校验
    */
   public UnifiedOrderRQ preCheck() {
      if(StringUtils.isEmpty(this.getCurrency())){
         throw new ParamException("货币类型[currency]参数不能为空");
      }
      if(StringUtils.isEmpty(this.getMchOrderNo())){
         throw new ParamException("商户请求流水号[mchOrderNo]参数不能为空");
      }
      if(this.getAmount() == null || this.getAmount() < 0){
         throw new ParamException("交易金额[amount]参数不能为空或参数格式不合法");
      }
      if(this.getMchOrderNo().length() > 32 ){
         throw new ParamException("商户请求流水号[mchOrderNo]长度不允许超过32位");
      }
      if(StringUtils.isEmpty(this.getSubject())){
         throw new ParamException("订单标题[subject]参数不能为空");
      }
      if(StringUtils.isEmpty(this.getStoreId())){
         throw new ParamException("门店ID[storeId]参数不能为空");
      }
      if(this.getExpiredTime() != null && (this.getExpiredTime() < 5 || this.getExpiredTime() > 1440)){
         throw new ParamException("订单过期时间[expiredTime]参数需要介于5-1440分钟之间");
      }
      if(this.getLimitPay() == null){
         this.setLimitPay(-1);
      }
      if(StringUtils.isEmpty(this.getAuthCode())){
         throw new ParamException("付款码[authCode]参数不能为空");
      }
      JSONObject channelExtra = new JSONObject();
      channelExtra.put("authCode",this.getAuthCode());
      String wayCode = JeepayKit.getPayWayCodeByBarCode(this.getAuthCode());
      if(CS.PAY_WAY_CODE.WX_BAR.equals(wayCode)){
         if(StringUtils.isEmpty(this.getSubAppid())){
            throw new ParamException("微信支付，子商户[subAppid]参数不能为空");
         }
         channelExtra.put("subAppid",this.getSubAppid());
      }
      this.setWayCode(wayCode);
      this.setChannelExtra(channelExtra.toString());
      return this;
   }

}
