package com.bohuikeji.delivery.backstage.entity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bohuikeji.frame.module.admin.annotation.TableNewField;
import com.bohuikeji.frame.module.admin.annotation.TableShowField;
import com.bohuikeji.frame.module.admin.base.EntityBase;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import com.baomidou.mybatisplus.annotation.TableField;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import jodd.http.HttpRequest;
import jodd.http.HttpResponse;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;

/**
 * <p>
 * 订单回调通知日志
 * </p>
 *
 * @author 10552
 * @since 2021-06-08
 */
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
@ApiModel(value="TOpenCallbackLog对象", description="订单回调通知日志")
@Slf4j
public class TOpenCallbackLog extends EntityBase<TOpenCallbackLog> {

    private static final long serialVersionUID = 1L;

    @TableId(value = "id", type = IdType.AUTO)
    @TableShowField(value = "ID",id = true)
    @TableNewField(show = false)
    private Integer id;

    @ApiModelProperty(value = "回调ID")
    @TableField("callback_id")
    @TableShowField("回调ID")
    @TableNewField
    private Integer callbackId;

    @ApiModelProperty(value = "开放平台账户ID")
    @TableField("open_id")
    @TableShowField("开放平台账户ID")
    @TableNewField
    private Integer openId;

    @ApiModelProperty(value = "订单ID")
    @TableField("order_id")
    @TableShowField("订单ID")
    @TableNewField
    private Integer orderId;

    @ApiModelProperty(value = "订单号")
    @TableField("order_num")
    @TableShowField("订单号")
    @TableNewField
    private String orderNum;

    @ApiModelProperty(value = "回调地址")
    @TableField("callback_url")
    @TableShowField("回调地址")
    @TableNewField
    private String callbackUrl;

    @ApiModelProperty(value = "回调参数")
    @TableField("callback_pram")
    @TableShowField("回调参数")
    @TableNewField
    private String callbackPram;

    @ApiModelProperty(value = "回调执行状态")
    @TableField("callback_status")
    @TableShowField("回调执行状态")
    @TableNewField
    private String callbackStatus;

    /**
     * 回调结果
     */
    private String callBackRes;

    @ApiModelProperty(value = "错误信息")
    @TableField("callback_error")
    @TableShowField("错误信息")
    @TableNewField
    private String callbackError;

    @ApiModelProperty(value = "创建时间")
    @TableField("gmt_create")
    @TableShowField("创建时间")
    @TableNewField
    private LocalDateTime gmtCreate;

    @ApiModelProperty(value = "最后一次更新时间")
    @TableField("gmt_update")
    @TableShowField("最后一次更新时间")
    @TableNewField
    private LocalDateTime gmtUpdate;

    /**
     * 执行订单回调，成功返回true,失败返回false
     * 该防方法失败后，调用业务应该按策略发起重试
     * @param callback 订单回调绑定对象
     * @param orderStatus 订单状态（变更后的）
     * @return
     */
    public static boolean runCallBackAndSave(TOpenCallback callback,String orderStatus){
        HttpResponse res;
        TOpenCallbackLog callbackLog=new TOpenCallbackLog();
        callbackLog.setCallbackId(callback.getId());
        callbackLog.setCallbackPram("orderNum="+callback.getOrderNum()+"&"+"orderStatus="+orderStatus);
        callbackLog.setOpenId(callback.getOpenId());
        callbackLog.setOrderNum(callback.getOrderNum());
        callbackLog.setCallbackUrl(callback.getCallbackUrl());
        callbackLog.setCallbackStatus("success");
        //执行请求，若失败，写入失败日志，返回false
        try{
            res=HttpRequest.get(callback.getCallbackUrl())
                    .query("orderNum",callback.getOrderNum())
                    .query("orderStatus",orderStatus)
                    .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE,"UTF-8").send();
        }catch (Exception e){
            callbackLog.setCallbackError(e.getMessage()+";"+e.getStackTrace()[0].toString());
            callbackLog.setCallbackStatus("error");
            log.error("【开放平台订单回调失败】{};{}",e.getMessage(),e.getStackTrace()[0]);
            callbackLog.insert();
            return false;
        }
        //请求成功，判断甲方系统接口返回值，若返回SUCCESS，表示成功，返回true，其他视为失败，写入失败日志，返回false
        String resStr=res.charset("UTF-8").bodyText();
        callbackLog.setCallBackRes(resStr);
        if (!"SUCCESS".equals(resStr)){
            callbackLog.setCallbackStatus("fail");
            callbackLog.insert();
            return false;
        }
        return callbackLog.insert();
    }
}
