package com.bohuikeji.delivery.backstage.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bohuikeji.delivery.backstage.constants.payConst;
import com.bohuikeji.delivery.backstage.entity.*;
import com.bohuikeji.delivery.backstage.entity.rental.TRentalCarOrder;
import com.bohuikeji.delivery.backstage.entity.rental.TRentalPay;
import com.bohuikeji.delivery.backstage.entity.wx.TWxUser;
import com.bohuikeji.delivery.backstage.listener.pay.PayTimoutListener;
import com.bohuikeji.delivery.backstage.mapper.TRentalPayMapper;
import com.bohuikeji.delivery.backstage.service.ITCustomerService;
import com.bohuikeji.delivery.backstage.service.ITRentalCarOrderService;
import com.bohuikeji.delivery.backstage.service.ITRentalPayService;
import com.bohuikeji.delivery.backstage.service.IWxUserService;
import com.bohuikeji.frame.module.admin.base.ServiceImplBase;
import com.bohuikeji.frame.module.admin.component.MqTool;
import com.bohuikeji.frame.module.admin.component.RedisUtil;
import com.bohuikeji.frame.module.admin.entity.back.APIEntity;
import com.bohuikeji.frame.module.admin.entity.vo.AliReturnPayVo;
import com.bohuikeji.frame.module.admin.utils.NumberUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;

/**
 * <p>
 * 货架信息表 服务实现类
 * </p>
 *
 * @author 10552
 * @since 2019-08-22
 */
@Data
@Slf4j
@Service
public class TRentalPayServiceImpl extends ServiceImplBase<TRentalPayMapper, TRentalPay> implements ITRentalPayService {
    @Autowired
    ITCustomerService customerService;
    @Autowired
    ITRentalPayService rentalPayService;
    @Autowired
    ITRentalCarOrderService rentalCarOrderService;
    @Autowired
    IWxUserService wxUserService;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    MqTool mqTool;

    /**
     * 订单业务创建预支付单（微信，支付宝）
     * @return
     */
    @Override
    public TRentalPay createBeforePay(TRentalCarOrder carOrder, String payMethod, String payWay) {
        TRentalPay rentalPay=new TRentalPay();
        rentalPay.setPayStatus("待付款");
        rentalPay.setRentalPlayerId(carOrder.getPlayerId());
        rentalPay.setRentalPayNum(NumberUtils.get("C"));
        rentalPay.setRentalOrderNum(carOrder.getRentalOrderNum());
        rentalPay.setRentalId(carOrder.getRentalId());
        rentalPay.setPayExpectPrice(new BigDecimal(carOrder.getRentalExpectPrice().toString()));
        rentalPay.setCreateTime(LocalDateTime.now());
        rentalPay.setPayMethod(payMethod);
        rentalPay.setRentalPayWay(payWay);
        this.save(rentalPay);
        mqTool.sendDelayMsg(rentalPay.getRentalPayNum(), PayTimoutListener.class, Duration.ofHours(3));
        return rentalPay;
    }

    @Override
    public APIEntity getPayAPIEntity(TRentalCarOrder carOrder, HttpServletRequest request) throws Exception {
        TCustomer customer = customerService.getById(carOrder.getPlayerId());
        String openId = null;
        //创建预支付订单
        TRentalPay rentalPay  =rentalPayService.createBeforePay(carOrder,"出租服务", payConst.getway(carOrder.getType()));
        if("JSAPI".equals(carOrder.getType())){
            openId = customer.getOpenId();
        }
        if("aliClient".equals(carOrder.getType())){
            TWxUser wxUser = wxUserService.getOne(new QueryWrapper<TWxUser>().eq("user_id",customer.getCustomerId()).eq("wx_app_type","ALICLIENT"));
            if(wxUser == null){
                return APIEntity.fail("请用户授权");
            }
            openId = wxUser.getWxUserOpenid();
        }
        if("kuaiShou".equals(carOrder.getType())){
            TWxUser wxUser = wxUserService.getOne(new QueryWrapper<TWxUser>().eq("user_id",customer.getCustomerId()).eq("wx_app_type","KUAISHOU"));
            if(wxUser == null){
                return APIEntity.fail("请用户授权");
            }
            openId = wxUser.getWxUserOpenid();
        }
        String payNum = rentalPay.getRentalPayNum();
        JSONObject object;
        if("急送平台".equals(carOrder.getOrderChannel())){
            object = payConst.getAliObject(carOrder.getType(),carOrder.getOrderChannel(),payNum,openId,carOrder.getRentalExpectPrice(),request);
        }else {
            object = payConst.getObject(carOrder.getType(),payNum,openId,carOrder.getRentalExpectPrice(),request);
        }
        //JSONObject object = payConst.getObject(carOrder.getType(),payNum,openId,carOrder.getRentalExpectPrice(),request);
        return object==null?APIEntity.fail("客户调起"+payConst.getway(carOrder.getType())+"支付错误"):APIEntity.success(object);
    }

    /**
     * 支付宝支付回调业务处理
     * @param req
     * @param pay
     * @return
     */
    @Override
    public TRentalPay aliCallbackPay(AliReturnPayVo req,TRentalPay rentalPay) {
        log.info("进入支付宝 支付业务处理：{}",req);
        TRentalCarOrder carOrder=redisUtil.get("carOrder:rental:num:"+rentalPay.getRentalOrderNum(),TRentalCarOrder.class);
        //rentalPayService.updateById(PayServices.orderPaySrevice(null,req,rentalPay));
        TRentalCarOrder rentalCarOrder = this.saveOrder(carOrder,rentalPay);
        rentalPay.setPayExpectPrice(rentalCarOrder.getRentalExpectPrice());
        rentalPay.setPayFactPrice(rentalCarOrder.getRentalExpectPrice());
        rentalPay.setRentalId(rentalCarOrder.getRentalId());
        rentalPay.setPayChannelNum(req.getTrade_no());
        rentalPay.setPayStatus("已支付");
        rentalPay.setPayChannel("支付宝");
        rentalPay.setPayTime(LocalDateTime.now());
        rentalPayService.updateById(rentalPay);//更新支付记录种订单id
        redisUtil.del("carOrder:rental:num:"+req.getOut_trade_no());
        //mqTool.sendMsg(order.getOrderNum(), OrderAliCenterListener.class);
        return rentalPay;
    }

    /**
     * 微信支付回调业务处理（不是微信扫码）
     * @param jsonObject
     * @param rentalPay
     * @return
     */
    @Override
    public TRentalPay wxCallbackPay(JSONObject jsonObject,TRentalPay rentalPay) {
        TRentalCarOrder carOrder = redisUtil.get("carOrder:rental:num:"+rentalPay.getRentalOrderNum(),TRentalCarOrder.class);
        //rentalPayService.updateById(PayServices.orderPaySrevice(jsonObject,null,rentalPay));
        TRentalCarOrder rentalCarOrder = this.saveOrder(carOrder,rentalPay);
        rentalPay.setPayExpectPrice(rentalCarOrder.getRentalExpectPrice());
        rentalPay.setRentalId(rentalCarOrder.getRentalId());
        rentalPayService.updateById(rentalPay);//更新支付记录种订单id
        redisUtil.del("order:create:num:"+jsonObject.getString("tpOrderId"));//下单支付完成后删除缓存种的数据
        log.info("支付记录信息："+rentalPay);
        return rentalPay;
    }


    /**
     * 订单业务、补充支付信息处理
     * @param carOrder
     * @param rentalPay
     * @return
     */
    private TRentalCarOrder saveOrder(TRentalCarOrder carOrder,TRentalPay rentalPay){
        log.info("@@@@@@@@@业务支付开始日志@@@@@@@@@");
        //支付成功计算佣金
        carOrder.setRentalOrderStatus("待接单");
        carOrder.setRentalFactPrice(carOrder.getRentalFactPrice().add(rentalPay.getPayExpectPrice()));
        rentalCarOrderService.save(carOrder);
            /*long minutes = ChronoUnit.MINUTES.between(LocalDateTime.now(), order.getSurplusPickTime());
            //设置订单延时(订单自动超时)操作
            mqTool.sendDelayMsg(order.getOrderNum(), OrderDelayCancelListener.class,Duration.ofMinutes(minutes));*/
        return carOrder;
    }
}
