package cn.newfeifan.mall.module.trade.service.ordercallbacklogs;

import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import cn.newfeifan.mall.module.trade.controller.admin.ordercallbacklogs.vo.*;
import cn.newfeifan.mall.module.trade.dal.dataobject.ordercallbacklogs.OrderCallbackLogsDO;
import cn.newfeifan.mall.framework.common.pojo.PageResult;
import cn.newfeifan.mall.framework.common.util.object.BeanUtils;

import cn.newfeifan.mall.module.trade.dal.mysql.ordercallbacklogs.OrderCallbackLogsMapper;

import static cn.newfeifan.mall.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.newfeifan.mall.module.trade.enums.ErrorCodeConstants.*;

/**
 * 第三方回调日志 Service 实现类
 *
 * @author 非繁人
 */
@Service
@Validated
public class OrderCallbackLogsServiceImpl implements OrderCallbackLogsService {

    @Resource
    private OrderCallbackLogsMapper orderCallbackLogsMapper;

    @Override
    public Long createOrderCallbackLogs(OrderCallbackLogsSaveReqVO createReqVO) {
        // 插入
        OrderCallbackLogsDO orderCallbackLogs = BeanUtils.toBean(createReqVO, OrderCallbackLogsDO.class);
        orderCallbackLogsMapper.insert(orderCallbackLogs);
        // 返回
        return orderCallbackLogs.getId();
    }

    @Override
    public void updateOrderCallbackLogs(OrderCallbackLogsSaveReqVO updateReqVO) {
        // 校验存在
        validateOrderCallbackLogsExists(updateReqVO.getId());
        // 更新
        OrderCallbackLogsDO updateObj = BeanUtils.toBean(updateReqVO, OrderCallbackLogsDO.class);
        orderCallbackLogsMapper.updateById(updateObj);
    }

    @Override
    public void deleteOrderCallbackLogs(Long id) {
        // 校验存在
        validateOrderCallbackLogsExists(id);
        // 删除
        orderCallbackLogsMapper.deleteById(id);
    }

    private void validateOrderCallbackLogsExists(Long id) {
        if (orderCallbackLogsMapper.selectById(id) == null) {
            throw exception(ORDER_CALLBACK_LOGS_NOT_EXISTS);
        }
    }

    @Override
    public OrderCallbackLogsDO getOrderCallbackLogs(Long id) {
        return orderCallbackLogsMapper.selectById(id);
    }

    @Override
    public PageResult<OrderCallbackLogsDO> getOrderCallbackLogsPage(OrderCallbackLogsPageReqVO pageReqVO) {
        return orderCallbackLogsMapper.selectPage(pageReqVO);
    }

    @Override
    public void create(String orderId, String param, String responseBody, String status) {
        boolean flag = status.equals("200");
        OrderCallbackLogsDO build = OrderCallbackLogsDO.builder().orderId(orderId).requestParam(param).responseBody(responseBody).status(flag).build();
        orderCallbackLogsMapper.insert(build);
    }

}