package com.yonge.cooleshow.portal.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.yonge.cooleshow.mbg.mapper.*;
import com.yonge.cooleshow.mbg.model.*;

import com.yonge.cooleshow.mbg.model.OmsOrderReturnApply;
import com.yonge.cooleshow.mbg.model.OmsOrderReturnApplyExample;
import com.yonge.cooleshow.mbg.model.UserOrderRefund;

import com.yonge.cooleshow.portal.dao.OmsOrderReturnApplyDao;
import com.yonge.cooleshow.portal.domain.OmsOrderReturnApplyParam;
import com.yonge.cooleshow.portal.dto.OmsOrderReturnApplyResult;
import com.yonge.cooleshow.portal.dto.OmsOrderReturnApplyVo;
import com.yonge.cooleshow.portal.dto.OmsReturnApplyDto;
import com.yonge.cooleshow.portal.dto.OmsReturnApplyQueryParam;
import com.yonge.cooleshow.portal.service.OmsPortalOrderReturnApplyService;
import com.yonge.cooleshow.portal.service.UmsMemberService;
import com.yonge.toolset.base.exception.BizException;

import com.yonge.toolset.payment.base.enums.TradeStatusEnum;
import com.yonge.toolset.payment.base.model.callback.PaymentCallBack;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 订单退货管理Service实现类
 * Created by macro on 2018/10/17.
 */
@Service
public class OmsPortalOrderReturnApplyServiceImpl implements OmsPortalOrderReturnApplyService {

    private static final Logger log = LoggerFactory.getLogger(OmsPortalOrderReturnApplyServiceImpl.class);

    @Autowired
    private OmsOrderReturnApplyMapper returnApplyMapper;

    @Autowired
    private OmsOrderReturnApplyDao returnApplyDao;

    @Autowired
    private UmsMemberService memberService;

    @Autowired
    private OmsOrderItemMapper  orderItemMapper;

    @Autowired
    private PmsProductMapper pmsProductMapper;

    @Autowired
    private PmsSkuStockMapper skuStockMapper;

    @Autowired
    private UserOrderRefundMapper userOrderRefundMapper;

    @Autowired
    private OmsOrderMapper omsOrderMapper;


    @Override
    public int create(OmsOrderReturnApplyParam returnApply) {
        OmsOrderReturnApply realApply = new OmsOrderReturnApply();
        BeanUtils.copyProperties(returnApply,realApply);
        OmsOrderItem omsOrderItem = orderItemMapper.selectByPrimaryKey(realApply.getOrderItemId());
        if (omsOrderItem == null || !omsOrderItem.getOrderId().equals(realApply.getOrderId())) {
            throw new BizException("当前订单不能退款");
        }
        OmsOrder order = omsOrderMapper.selectByPrimaryKey(realApply.getOrderId());
        if (order == null) {
            throw new BizException("订单不存在");
        }
        realApply.setOrderSn(order.getOrderSn());
        PmsProduct pmsProduct = pmsProductMapper.selectByPrimaryKey(omsOrderItem.getProductId());
        realApply.setProductPic(pmsProduct.getPic());
        realApply.setProductName(pmsProduct.getName());
        realApply.setProductBrand(pmsProduct.getBrandName());
        if (omsOrderItem.getProductSkuId() != null) {
            PmsSkuStock pmsSkuStock = skuStockMapper.selectByPrimaryKey(omsOrderItem.getProductSkuId());
            realApply.setProductAttr(pmsSkuStock.getSpData());
        }
        realApply.setProductPrice(omsOrderItem.getProductPrice());
        realApply.setProductRealPrice(omsOrderItem.getRealAmount());
        realApply.setPrecisionAmount(omsOrderItem.getPrecisionAmount());
        realApply.setCreateTime(new Date());
        realApply.setStatus(0);
        return returnApplyMapper.insert(realApply);
    }

    @Override
    public int delete(Long id) {
        List<Integer> status  = new ArrayList<>();
        status.add(0);
        status.add(1);
        OmsOrderReturnApplyExample example = new OmsOrderReturnApplyExample();
        example.createCriteria().andIdEqualTo(id).andStatusIn(status);
        return returnApplyMapper.deleteByExample(example);

    }

    @Override
    public OmsOrderReturnApplyResult getItem(Long id) {
        return returnApplyDao.getDetail(id);
    }

    @Override
    public List<OmsOrderReturnApplyVo> list(OmsReturnApplyQueryParam queryParam, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        UmsMember currentMember = memberService.getCurrentMember();
        if (currentMember == null) {
            throw  new BizException("请重新登录");
        }
        queryParam.setMemberId(currentMember.getId());
        return returnApplyDao.getList(queryParam);
    }

    @Override
    public void setDeliverySn(OmsReturnApplyDto applyDto) {
        OmsOrderReturnApply omsOrderReturnApply = new OmsOrderReturnApply();
        omsOrderReturnApply.setId(applyDto.getId());
        omsOrderReturnApply.setDeliverySn(applyDto.getDeliverySn());
        returnApplyMapper.updateByPrimaryKeySelective(omsOrderReturnApply);
    }

    @Override
    public void refundPaymentCallBack(PaymentCallBack data) {

        log.info("退款回调信息： {}",JSON.toJSONString(data));
        if (TradeStatusEnum.succeeded.equals(data.getStatus())) {//退款成功
            paymentRefundSucceededHandle(data);
        } else if (TradeStatusEnum.failed.equals(data.getStatus())) {//退款失败
            paymentRefundFailedHandle(data, data.getErrMsg());
        }
    }

    /**
     * 退款失败
     */
    private void paymentRefundFailedHandle(PaymentCallBack data, String errMsg) {
        if (data == null) {
            return;
        }
        UserOrderRefund userOrderRefund = userOrderRefundMapper.selectByRefundNo(
                data.getRefundPaymentCallBack().getBillNo());
        userOrderRefund.setArrivalTime(new Date());
        userOrderRefund.setStatus(TradeStatusEnum.failed.getCode());
        userOrderRefund.setPayFailMsg(errMsg);
        userOrderRefund.setTransNo(data.getRefundPaymentCallBack().getTransNo());

        userOrderRefundMapper.updateByPrimaryKeySelective(userOrderRefund);
    }

    /**
     * 退款成功
     */
    private void paymentRefundSucceededHandle(PaymentCallBack data) {

        log.info("refund info is {}", JSON.toJSONString(data));
        if (data == null) {
            return;
        }
        UserOrderRefund userOrderRefund = userOrderRefundMapper.selectByRefundNo(
                data.getRefundPaymentCallBack().getBillNo());
        userOrderRefund.setArrivalTime(new Date());
        userOrderRefund.setStatus(TradeStatusEnum.succeeded.getCode());
        userOrderRefund.setTransNo(data.getRefundPaymentCallBack().getTransNo());
        userOrderRefund.setFeeAmt(new BigDecimal(data.getRefundPaymentCallBack().getFeeAmt()));
        userOrderRefund.setRefundAmt(new BigDecimal(data.getRefundPaymentCallBack().getRefundAmt()));

        userOrderRefundMapper.updateByPrimaryKeySelective(userOrderRefund);
    }
}

