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

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.yonge.cooleshow.admin.dao.OmsOrderReturnApplyDao;
import com.yonge.cooleshow.admin.dto.*;
import com.yonge.cooleshow.api.feign.AdminFeignService;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
import com.yonge.cooleshow.common.entity.MallOrderItemDto;
import com.yonge.cooleshow.common.enums.PostStatusEnum;
import com.yonge.cooleshow.common.service.IdGeneratorService;
import com.yonge.cooleshow.mall.common.exception.ApiException;
import com.yonge.cooleshow.mall.common.service.RedisService;
import com.yonge.cooleshow.mbg.mapper.OmsOrderItemMapper;
import com.yonge.cooleshow.mbg.model.*;
import com.yonge.toolset.base.exception.BizException;
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.admin.service.OmsOrderReturnApplyService;
import com.yonge.toolset.base.result.BaseResult;
import com.yonge.toolset.payment.base.enums.OpenEnum;
import com.yonge.toolset.payment.base.enums.PayChannelEnum;
import com.yonge.toolset.payment.base.enums.PaymentClientEnum;
import com.yonge.toolset.payment.base.enums.TradeStatusEnum;
import com.yonge.toolset.payment.base.model.RefundBill;
import com.yonge.toolset.payment.core.service.PaymentClient;
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.math.RoundingMode;
import java.util.ArrayList;
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 OmsOrderItemMapper orderItemMapper;

    @Autowired
    private AdminFeignService adminFeignService;
    @Autowired
    private RedisService redisService;
    private String REDIS_KEY_ORDER_ID= "redis.key.orderId";
    private String REDIS_DATABASE = "redis.database";
    @Autowired
    private PaymentClient paymentClient;

    @Autowired
    private UserOrderPaymentMapper userOrderPaymentMapper;

    @Autowired
    private IdGeneratorService idGeneratorService;

    @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);
        List<OmsOrderReturnApply> omsOrderReturnApplies = returnApplyMapper.selectByExample(example);
        if (omsOrderReturnApplies.size() != ids.size()) {
            throw new BizException("只能删除已拒绝的退货订单");
        }
        return returnApplyMapper.deleteByExample(example);
    }

    @Override
    public int updateStatus(Long id, OmsUpdateStatusParam statusParam) {
        Integer status = statusParam.getStatus();
        OmsOrderReturnApply omsOrderReturnApply = returnApplyMapper.selectByPrimaryKey(id);
        if (omsOrderReturnApply == null) {
            throw new BizException("退货订单不存在或被撤销");
        }
        if (omsOrderReturnApply.getProductRealPrice().multiply(BigDecimal.valueOf(omsOrderReturnApply.getProductCount())).compareTo(statusParam.getReturnAmount()) <0) {
            throw new BizException("退款金额不能大于商品金额");
        }
        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());
            if (omsOrderReturnApply.getReturnAmount().compareTo(BigDecimal.ZERO) >0) {
                refundAmount(omsOrderReturnApply);
            }

            // 确认退款 取消平台收入和 分润
            setRecord(omsOrderReturnApply);

        } 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);
    }


    @Override
    public void setTestReturnApply(Long id) {
        OmsOrderReturnApply returnApply = returnApplyMapper.selectByPrimaryKey(id);
        returnApply.setId(id);
        returnApply.setStatus(2);
        returnApply.setReceiveTime(new Date());
        returnApply.setReceiveMan("测试退货");
        returnApply.setReceiveNote("测试退货");

        // 确认退款 取消平台收入和 分润
        setRecord(returnApply);
        returnApplyMapper.updateByPrimaryKeySelective(returnApply);
    }

    private void setRecord(OmsOrderReturnApply returnApply) {
        if (returnApply.getOrderItemId() != null) {
            OmsOrderItem omsOrderItem = orderItemMapper.selectByPrimaryKey(returnApply.getOrderItemId());
            if (omsOrderItem != null) {
                MallOrderItemDto teacherShareDto = new MallOrderItemDto();
                BeanUtils.copyProperties(omsOrderItem, teacherShareDto);
                teacherShareDto.setRealAmount(omsOrderItem.getRealAmount().multiply(BigDecimal.valueOf(omsOrderItem.getProductQuantity())));
                teacherShareDto.setProductSkuId(omsOrderItem.getProductSkuId());
                teacherShareDto.setStatus(PostStatusEnum.CANCEL);
                List<MallOrderItemDto> list = new ArrayList<>();
                list.add(teacherShareDto);
                HttpResponseResult<Boolean> result = adminFeignService.mallRecordState(list);

                if (result.getStatus()) {
                    log.debug("分润取消写入成功，json: {}", JSON.toJSONString(teacherShareDto));
                } else {
                    log.error("分润取消写入失败，json: {}",JSON.toJSONString(teacherShareDto));
                }
            }
        }
    }

    /**
     * 退款处理
     *
     * @param returnApply 退款信息
     */
    private void refundAmount(OmsOrderReturnApply returnApply) {
        // 退款
        UserOrderPayment userOrderPayment = userOrderPaymentMapper.selectByOrderNoAndStatusSucceeded(returnApply.getOrderSn());
        if (userOrderPayment == null) {
            throw new ApiException("未找到付款信息");
        }
        String orderSn = generateOrderSn(returnApply);

        RefundBill refundReq = new RefundBill(OpenEnum.valueOf(userOrderPayment.getOpenType()),
                PaymentClientEnum.valueOf(userOrderPayment.getPaymentClient()), PayChannelEnum.valueOf(userOrderPayment.getPayChannel()));
        refundReq.setRefundNo(orderSn);
        refundReq.setRefundAmt(returnApply.getReturnAmount().setScale(2, RoundingMode.HALF_UP));

        refundReq.setReason(returnApply.getProductName());
        refundReq.setPaymentNo(userOrderPayment.getAdapayNo());
        refundReq.setTradeNo(userOrderPayment.getTransNo());
        refundReq.setOrderAmt(userOrderPayment.getPayAmt());
        BaseResult<RefundBill> refundBillBaseResult = paymentClient.refundPayment(refundReq);
        if (refundBillBaseResult.getStatus()) {
            RefundBill refundBill = refundBillBaseResult.getData();
            UserOrderRefund userOrderRefund = new UserOrderRefund();
            userOrderRefund.setReturnId(returnApply.getId());
            userOrderRefund.setOrderNo(orderSn);
            userOrderRefund.setPayTransNo(userOrderPayment.getTransNo());
            userOrderRefund.setRefundAmt(refundBill.getRefundAmt());
            userOrderRefund.setStatus(TradeStatusEnum.pending.getCode());
            userOrderRefund.setPayOrderNo(userOrderPayment.getOrderNo());
            userOrderRefundMapper.insert(userOrderRefund);
        } else {
            throw new BizException(refundBillBaseResult.getMsg());
        }
    }

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


    @Override
    public HomeStatistical countReturnStatus() {

        return returnApplyDao.selectReturnStatusCount();
    }


    /**
     * 生成18位退款订单编号:8位日期+2位平台号码+2位支付方式+6位以上自增id
     */
    private String generateOrderSn(OmsOrderReturnApply returnApply) {
        return String.valueOf(idGeneratorService.generatorId("refund"));
    }
}
