package com.jpsoft.shinestar.modules.base.service.impl;

import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jpsoft.shinestar.modules.base.dao.OrderInfoDAO;
import com.jpsoft.shinestar.modules.base.entity.GoodsInfo;
import com.jpsoft.shinestar.modules.base.entity.OrderInfo;
import com.jpsoft.shinestar.modules.base.entity.OrderLog;
import com.jpsoft.shinestar.modules.base.service.GoodsInfoService;
import com.jpsoft.shinestar.modules.base.service.OrderInfoService;
import com.jpsoft.shinestar.modules.base.service.OrderLogService;
import com.jpsoft.shinestar.modules.base.service.TransferService;
import com.jpsoft.shinestar.modules.business.entity.CameraPurchaser;
import com.jpsoft.shinestar.modules.business.service.CameraPurchaserService;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.sys.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author 墨鱼_mo
 * @date 2020-10-17 12:42
 */
@Transactional
@Component(value = "orderInfoService")
@Slf4j
public class OrderInfoServiceImpl implements OrderInfoService {
    @Autowired
    private CameraPurchaserService cameraPurchaserService;
    @Autowired
    private GoodsInfoService goodsInfoService;
    @Resource
    private OrderInfoDAO orderInfoDAO;
    @Autowired
    private OrderLogService orderLogService;
    @Autowired
    private TransferService transferService;


    @Override
    public OrderInfo get(String id) {
        return orderInfoDAO.get(id);
    }

    @Override
    public int insert(OrderInfo model) {
        // TODO Auto-generated method stub
        //model.setId(UUID.randomUUID().toString());
        /*OrderLog orderLog = new OrderLog();
        orderLog.setId(UUID.randomUUID().toString());
        orderLog.setCreateBy(model.getCreateBy());
        orderLog.setCreateTime(new Date());
        orderLog.setOrderId(model.getId());
        orderLog.setContent("创建了订单");
        orderLogService.insert(orderLog);*/

       /* //发送延时消息，5分钟后如果未支付自动关闭订单
        rabbitTemplate.convertAndSend("orderDelayExchange", "submit", model.getId(), (message) -> {
            //延时单位毫秒
            message.getMessageProperties().setHeader("x-delay", orderCloseTimeoutSeconds * 1000);
            return message;
        });*/

        return orderInfoDAO.insert(model);
    }

    @Override
    public int update(OrderInfo model) {
        // TODO Auto-generated method stub
        return orderInfoDAO.update(model);
    }

    @Override
    public int updateAndPayIsOff(OrderInfo model, User user) {
        int count = orderInfoDAO.update(model);

        OrderLog orderLog = new OrderLog();
        orderLog.setCreateBy(user.getRealName());
        orderLog.setContent("线下退款成功");
        orderLog.setOrderId(model.getId());
        orderLogService.insert2(orderLog);

        return count;
    }

    @Override
    public int updateAndPay(OrderInfo model, Integer payStatus, User user) throws Exception {
        int count = 0;

        //支付类型为微信
        if (("wechat").equals(model.getPayName())) {
            if (payStatus == 40) {
                //调用退款接口
                boolean flag = transferService.refund(model.getOutOrderNo());
                if (flag) {
                    count = orderInfoDAO.update(model);
                    OrderLog orderLog = new OrderLog();
                    orderLog.setCreateBy(user.getRealName());
                    orderLog.setContent("线上退款成功");
                    orderLog.setOrderId(model.getId());
                    orderLogService.insert2(orderLog);
                }
            }
        } else if (("alipay").equals(model.getPayName())) {
            if (payStatus == 40) {
                //调用退款接口
                boolean flag = transferService.aliPayRefund(model.getOutOrderNo());
                if (flag) {
                    count = orderInfoDAO.update(model);
                    OrderLog orderLog = new OrderLog();
                    orderLog.setCreateBy(user.getRealName());
                    orderLog.setContent("线上退款成功");
                    orderLog.setOrderId(model.getId());
                    orderLogService.insert2(orderLog);
                }
            }
        } else {
            count = orderInfoDAO.update(model);
        }

        return count;
    }


    @Override
    public int delete(String id) {
        // TODO Auto-generated method stub
        return orderInfoDAO.delete(id);
    }

    @Override
    public boolean exist(String id) {
        // TODO Auto-generated method stub
        int count = orderInfoDAO.exist(id);

        return count > 0 ? true : false;
    }

    @Override
    public List<OrderInfo> list() {
        // TODO Auto-generated method stub
        return orderInfoDAO.list();
    }


    @Override
    public Page<OrderInfo> pageSearch(Map<String, Object> searchParams, int pageNumber, int pageSize, boolean count, List<Sort> sortList) {
        Page<OrderInfo> page = PageHelper.startPage(pageNumber, pageSize, count).doSelectPage(() -> {
            orderInfoDAO.search(searchParams, sortList);
        });

        return page;
    }

    @Override
    public OrderInfo findByOutOrderNo(String outTradeNo) {
        return orderInfoDAO.findByOutOrderNo(outTradeNo);
    }

    @Override
    public void orderNotifyLogical(OrderInfo orderInfo) {

        GoodsInfo info=goodsInfoService.get(orderInfo.getGoodsId());
        if ("1".equals(orderInfo.getType())) {
            CameraPurchaser cameraPurchaser=cameraPurchaserService.getByPersonId(orderInfo.getPersonId());
            boolean insert=true;
            if(cameraPurchaser==null){
                cameraPurchaser=new CameraPurchaser();
                cameraPurchaser.setId(UUID.randomUUID().toString());
                cameraPurchaser.setPersonId(orderInfo.getPersonId());
                cameraPurchaser.setDelFlag(false);
                cameraPurchaser.setCreateTime(new Date());
                cameraPurchaser.setEndTime(new Date());

            }else {
                insert=false;
                cameraPurchaser.setUpdateTime(new Date());
            }
            String days =info.getExpand1();

            Date newVipEndTime = null;
            //当前时间比结束时间大，则时间在当前时间上添加时间

            if (new Date().compareTo(cameraPurchaser.getEndTime())>0){
                newVipEndTime = DateUtil.offsetDay(new Date(), Integer.valueOf(days));
            }else {
                newVipEndTime = DateUtil.offsetDay(cameraPurchaser.getEndTime(), Integer.valueOf(days));
            }

            cameraPurchaser.setEndTime(newVipEndTime);
            if(insert){
                cameraPurchaserService.insert(cameraPurchaser);
            }else{
                cameraPurchaserService.update(cameraPurchaser);
            }
        }

    }


}
