package cn.freemud.adapter;

import com.alibaba.fastjson.JSONObject;
import com.freemud.application.sdk.api.ordercenter.enums.AfterSalesType;
import com.freemud.application.sdk.api.ordercenter.request.OrderCancelReq;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.OrderInfoReqs;
import com.freemud.sdk.api.assortment.order.enums.AfterSalesRefunStateEnum;
import com.freemud.sdk.api.assortment.order.enums.OperationClientEnum;
import org.apache.commons.lang.StringUtils;

import java.math.BigDecimal;

/**
 * @author Clover.z
 * @version 1.0.0
 * @since 1.0.0
 */
public class OrderCancelReqAdapter {

    public static OrderCancelReq convert(OrderInfoReqs order,
                                         String refundId,
                                         AfterSalesType afterSalesType,
                                         Long refundAmount,
                                         String reason,
                                         String remark,
                                         Boolean refundDeliveryFee,
                                         Byte refundMode) {
        OrderCancelReq req = new OrderCancelReq();
        if (StringUtils.isNotBlank(reason) && reason.length() > 50) {
            reason = reason.substring(0, 50);
        }
        //商户号必传
        req.setPartnerId(order.getPartnerId());
        req.setOrderCode(order.getOrderCode());
        req.setReqRemark(remark);
        req.setReqAmount(refundAmount != null ? new BigDecimal(refundAmount) : null);
        req.setIsPartRefund(refundAmount != null); // 是否部分退
        //售后单类型 1:其他取消 2:用户取消 3:商户取消 4:未支付超时关单 5:商户接单超时取消 6:商家拒单
        // 7:配送用户拒收 8:用户售后退货/售后退款 9:系统取消 10:客服取消 11:用户统一取消，
        req.setAfterSalesType(afterSalesType.getIndex());
        req.setOrderClient(order.getOrderClient());
        req.setCancelReason(reason);
        req.setAfterSalesReason(reason);
        req.setAfterSerialNo(refundId);

        // 商城订单 增加拓展信息
        if (null != refundMode) {
            JSONObject ext = new JSONObject();
            ext.put("refundMode", refundMode);
            req.setExtInfo(ext.toJSONString());
        }
        req.setRefundDeliveryAmount(refundDeliveryFee);
        req.setRefundState(AfterSalesRefunStateEnum.STATE_1.getIndex());
        //操作来源客户端 1:POS插件 2:小助手 3:开放平台 4:自动任务 5:用户端 6:系统 7:万象 8:太一
        if (AfterSalesType.SYSTEM_CANCEL.getIndex().equals(afterSalesType.getIndex())) {
            req.setOperator("admin");
            req.setOperationClient(OperationClientEnum.STATE_6.getIndex());
        } else {
            req.setOperationClient(OperationClientEnum.STATE_5.getIndex());
            req.setOperator(order.getUserName());
        }
        return req;
    }
}
