package cn.freemud.service.universal.impl;

import cn.freemud.adapter.OrderAdapter;
import cn.freemud.base.entity.BaseResponse;
import cn.freemud.constant.ResponseCodeConstant;
import cn.freemud.entities.bo.CreateOrderBo;
import cn.freemud.entities.dto.order.CreateOrderOperateDto;
import cn.freemud.entities.vo.CreateOrderBaseVo;
import cn.freemud.entities.vo.CreateOrderResponseVo;
import cn.freemud.enums.ResponseResult;
import cn.freemud.service.universal.UniversalOrderService;
import cn.freemud.utils.ResponseUtil;
import com.alibaba.fastjson.JSONObject;
import com.freemud.application.sdk.api.log.LogThreadLocal;
import com.freemud.application.sdk.api.ordercenter.enums.AfterSalesType;
import com.freemud.application.sdk.api.ordercenter.request.OrderExtInfoDto;
import com.freemud.application.sdk.api.ordercenter.request.create.CreateOrderRequest;
import com.freemud.sdk.api.assortment.order.request.order.CancelOrderRequest;
import com.freemud.sdk.api.assortment.order.request.order.OrderEditRequest;
import com.freemud.sdk.api.assortment.order.response.order.BaseOrderResponse;
import com.freemud.sdk.api.assortment.order.response.order.CreateOrderResponse;
import com.freemud.sdk.api.assortment.order.response.order.QueryOrdersResponse;
import org.apache.commons.lang.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author : xh.Z
 * @email : fisherman0510@163.com
 * @Date : 2021/4/9 下午2:31
 * @description : app订单
 */
@Service
public class AppOrderService extends UniversalOrderService {

    @Autowired
    private OrderAdapter orderAdapter;

    /**
     * @return false 不拉起微信预支付
     */
    @Override
    protected boolean defaultPrepayOrder() {
        return false;
    }

    @Override
    public void getCustomCreateOrderBo(CreateOrderBo createOrderBo) {

    }

    @Override
    public void validParam(CreateOrderBaseVo createOrderBaseVo) {

    }

    @Override
    protected CreateOrderRequest absGetCreateOrderRequest(CreateOrderBo createOrderBo) {
        // fisherman 可以直接转换对象 和其他的地方有 重复
        return super.createOrderAdapter.convent2CreateOrderRequest(createOrderBo);
    }

    /**
     * 拓展字段存放 app 和 saas 一致
     *
     * @param createOrderBo
     * @return
     */
    @Override
    public OrderExtInfoDto getExtInfo(CreateOrderBo createOrderBo) {
        OrderExtInfoDto extInfo = super.getExtInfoUniversal(createOrderBo);
        createOrderBo.setExtInfo(extInfo);
        return extInfo;
    }


    /**
     * 覆盖 父类创建订单方法
     *
     * @param createOrderBo
     * @return
     */
    @Override
    protected BaseResponse createSharedOrder(CreateOrderBo createOrderBo) {
        CreateOrderRequest request = this.absGetCreateOrderRequest(createOrderBo);
        if (request == null) {
            return ResponseUtil.error(ResponseResult.PARAMETER_MISSING);
        }

        // 创建订单
        BaseResponse createOrderOperateDtoResponse = this.subSendCreateOrder(request, createOrderBo);
        if (createOrderOperateDtoResponse == null || !ResponseResult.SUCCESS.getCode().equals(createOrderOperateDtoResponse.getCode()) || createOrderOperateDtoResponse.getResult() == null) {
            return createOrderOperateDtoResponse;
        }

        // app 业务独立逻辑
        CreateOrderOperateDto createOrderOperateDto = (CreateOrderOperateDto) createOrderOperateDtoResponse.getResult();
        BaseResponse baseResponse = this.updateOrderExtInfo(createOrderOperateDto.getProductOrderBean(), createOrderBo.getExtInfo(), LogThreadLocal.getTrackingNo());
        if (baseResponse != null) {
            return baseResponse;
        }
        //返回没创建预支付的结果
        CreateOrderResponseVo responseVo = orderAdapter.convent2CreateFatherSonOrderNoPayResponseVo(createOrderOperateDto.getProductOrderBean());
        return ResponseUtil.success(responseVo);
    }

    private BaseResponse subSendCreateOrder(CreateOrderRequest request, CreateOrderBo createOrderBo) {
        BaseResponse baseResponse = super.sendCreateOrder(request, createOrderBo);
        if (baseResponse == null || !ResponseResult.SUCCESS.getCode().equals(baseResponse.getCode()) || baseResponse.getResult() == null) {
            return baseResponse;
        }
        CreateOrderOperateDto response = new CreateOrderOperateDto();
        QueryOrdersResponse.DataBean.OrderBean result = (QueryOrdersResponse.DataBean.OrderBean) baseResponse.getResult();
        long totalAmount = result.getAmount();
        response.setTotalAmount(totalAmount);
        response.setCardAmount(0);
        response.setFatherOrderBean(result);
        response.setProductOrderBean(result);
        return ResponseUtil.success(response);
    }


    private BaseResponse updateOrderExtInfo(QueryOrdersResponse.DataBean.OrderBean orderBean, OrderExtInfoDto orderExtInfo, String trackingNo) {
        OrderEditRequest orderEditRequest = new OrderEditRequest(orderBean.getOid(), JSONObject.toJSONString(orderExtInfo));
        orderEditRequest.setTrackingNo(trackingNo);
        BaseOrderResponse baseOrderResponse = orderCenterSdkService.orderEdit(orderEditRequest);
        if (!ObjectUtils.equals(ResponseCodeConstant.RESPONSE_SUCCESS, baseOrderResponse.getErrcode())) {
            CancelOrderRequest cancelOrderRequest = orderAdapter.convent2CancelOrderRequest(orderBean.getOid(), orderBean.getCompanyId(),
                    AfterSalesType.SYSTEM_CANCEL, "编辑订单支付信息失败", trackingNo, null);
            orderCenterSdkService.orderCancel(cancelOrderRequest);
            return ResponseUtil.error(baseOrderResponse.getErrcode().toString(), baseOrderResponse.getErrmsg());
        }
        return null;
    }

    /**
     * 扣减库存订单
     *
     * @param createOrderBo
     * @param createOrderResponse
     * @return
     */
    @Override
    protected BaseResponse sendActivityUpdateStock(CreateOrderBo createOrderBo, CreateOrderResponse createOrderResponse) {
        return super.defalutSendActivityUpdateStock(createOrderBo, createOrderResponse);
    }
}
