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

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.yonge.cooleshow.admin.dao.OmsOrderReturnApplyDao;
import com.yonge.cooleshow.admin.dto.OmsOrderReturnApplyResult;
import com.yonge.cooleshow.admin.dto.OmsReturnApplyQueryParam;
import com.yonge.cooleshow.admin.dto.OmsUpdateStatusParam;
import com.yonge.cooleshow.common.exception.BizException;
import com.yonge.cooleshow.enums.PayStatusEnum;
import com.yonge.cooleshow.mbg.mapper.OmsOrderReturnApplyMapper;
import com.yonge.cooleshow.mbg.mapper.UserOrderPaymentMapper;
import com.yonge.cooleshow.mbg.mapper.UserOrderRefundMapper;
import com.yonge.cooleshow.mbg.model.OmsOrderReturnApply;
import com.yonge.cooleshow.mbg.model.OmsOrderReturnApplyExample;
import com.yonge.cooleshow.admin.service.OmsOrderReturnApplyService;
import com.yonge.cooleshow.mbg.model.UserOrderPayment;
import com.yonge.cooleshow.mbg.model.UserOrderRefund;
import com.yonge.cooleshow.sdk.req.OrderRefundReq;
import com.yonge.cooleshow.sdk.res.OrderRefundRes;
import com.yonge.cooleshow.service.PaymentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

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

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

    @Autowired
    private OmsOrderReturnApplyDao returnApplyDao;
    @Autowired
    private OmsOrderReturnApplyMapper returnApplyMapper;

    @Autowired
    private PaymentService adapayPaymentService;

    @Autowired
    private UserOrderPaymentMapper userOrderPaymentMapper;

    @Autowired
    private UserOrderRefundMapper userOrderRefundMapper;

    @Override
    public List<OmsOrderReturnApply> list(OmsReturnApplyQueryParam queryParam, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum,pageSize);
        return returnApplyDao.getList(queryParam);
    }

    @Override
    public int delete(List<Long> ids) {
        OmsOrderReturnApplyExample example = new OmsOrderReturnApplyExample();
        example.createCriteria().andIdIn(ids).andStatusEqualTo(3);
        return returnApplyMapper.deleteByExample(example);
    }

    @Override
    public int updateStatus(Long id, OmsUpdateStatusParam statusParam) {
        Integer status = statusParam.getStatus();
        OmsOrderReturnApply omsOrderReturnApply = returnApplyMapper.selectByPrimaryKey(id);
        if (omsOrderReturnApply.getStatus().equals(statusParam.getStatus())) {
            return 1;
        }
        OmsOrderReturnApply returnApply = new OmsOrderReturnApply();
        if(status.equals(1)){
            //确认退货
            returnApply.setId(id);
            returnApply.setStatus(1);
            returnApply.setReturnAmount(statusParam.getReturnAmount());
            returnApply.setCompanyAddressId(statusParam.getCompanyAddressId());
            returnApply.setHandleTime(new Date());
            returnApply.setHandleMan(statusParam.getHandleMan());
            returnApply.setHandleNote(statusParam.getHandleNote());
        }else if(status.equals(2)){
            //完成退货
            returnApply.setId(id);
            returnApply.setStatus(2);
            returnApply.setReceiveTime(new Date());
            returnApply.setReceiveMan(statusParam.getReceiveMan());
            returnApply.setReceiveNote(statusParam.getReceiveNote());
            refundAmount(returnApply);
        }else if(status.equals(3)){
            //拒绝退货
            returnApply.setId(id);
            returnApply.setStatus(3);
            returnApply.setHandleTime(new Date());
            returnApply.setHandleMan(statusParam.getHandleMan());
            returnApply.setHandleNote(statusParam.getHandleNote());
        }else{
            return 0;
        }
        return returnApplyMapper.updateByPrimaryKeySelective(returnApply);
    }

    /**
     * 退款处理
     *
     * @param returnApply 退款信息
     */
    private void refundAmount(OmsOrderReturnApply returnApply) {
        // 退款
        UserOrderPayment userOrderPayment = userOrderPaymentMapper.selectByOrderNo(returnApply.getOrderSn());
        OrderRefundReq refundReq = new OrderRefundReq();
        refundReq.setOrderNo(returnApply.getOrderSn());
        refundReq.setRefundAmount(returnApply.getReturnAmount().setScale(2, RoundingMode.HALF_UP).toString());
        refundReq.setReason(returnApply.getProductName());
        refundReq.setTransNo(userOrderPayment.getTransNo());
        OrderRefundRes orderRefundRes = adapayPaymentService.orderRefund(refundReq);
        if (orderRefundRes.isStatus()) {
            UserOrderRefund userOrderRefund = new UserOrderRefund();
            userOrderRefund.setOrderNo(orderRefundRes.getRefundOrderNo());
            userOrderRefund.setTransNo(orderRefundRes.getTransNo());
            userOrderRefund.setPayTransNo(orderRefundRes.getPayTransNo());
            userOrderRefund.setRefundAmt(new BigDecimal(orderRefundRes.getRefundAmount()));
            userOrderRefund.setStatus(orderRefundRes.getRefundStatus().getCode());
            userOrderRefundMapper.insert(userOrderRefund);
        } else {
            throw new BizException(orderRefundRes.getMessage());
        }
    }

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

    @Override
    public void orderCallback(String data) {
        JSONObject hfRes = JSONObject.parseObject(data);
        UserOrderRefund userOrderRefund = userOrderRefundMapper.selectByTransNo(hfRes.getString("id"));
        if (null == userOrderRefund) {
            log.error("汇付退款回调，订单未找到。 req is {}", data);
            return;
        }

        if (!userOrderRefund.getStatus().equals(PayStatusEnum.pending.getCode())) {
            log.error("汇付退款回调，订单状态异常。 req is {}", data);
        }
        if (PayStatusEnum.succeeded.getCode().equals(hfRes.getString("status"))) {
            //退款成功
            refundSuccess(userOrderRefund, hfRes);
        } else {
            // 退款失败
            refundCancel(userOrderRefund,hfRes);
        }
    }

    /**
     * 退款失败
     *
     * @param userOrderRefund
     * @param hfRes
     */
    private void refundCancel(UserOrderRefund userOrderRefund, JSONObject hfRes) {
        userOrderRefund.setArrivalTime(new Date());
        userOrderRefund.setStatus(PayStatusEnum.failed.getCode());
        if (hfRes != null) {
            try {
                userOrderRefund.setPayFailMsg(hfRes.getString("error_msg"));
            }catch (Exception e) {
                log.error("退款订单，退款失败参数错误,参数{}", hfRes.toJSONString());
            }
        }
        userOrderRefundMapper.updateByPrimaryKeySelective(userOrderRefund);
    }

    /**
     * 退款成功
     *
     * @param userOrderRefund
     * @param hfRes
     */
    private void refundSuccess(UserOrderRefund userOrderRefund, JSONObject hfRes) {

        userOrderRefund.setArrivalTime(new Date());
        userOrderRefund.setStatus(PayStatusEnum.succeeded.getCode());
        if (hfRes != null) {
            try {
                userOrderRefund.setFeeAmt(hfRes.getBigDecimal("fee_amt"));
                userOrderRefund.setRefundAmt(hfRes.getBigDecimal("pay_amt"));
            }catch (Exception e) {
                log.error("退款订单，金额格式化失败,参数{}", hfRes.toJSONString());
            }
        }
        userOrderRefundMapper.updateByPrimaryKeySelective(userOrderRefund);


    }
}
