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

import com.alibaba.fastjson.JSONObject;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bohuikeji.delivery.backstage.entity.TCourier;
import com.bohuikeji.delivery.backstage.entity.TCourierPay;
import com.bohuikeji.delivery.backstage.listener.pay.PayTimoutListener;
import com.bohuikeji.delivery.backstage.mapper.TCourierPayMapper;
import com.bohuikeji.delivery.backstage.service.*;
import com.bohuikeji.frame.module.admin.base.ServiceImplBase;
import com.bohuikeji.frame.module.admin.component.MqTool;
import com.bohuikeji.frame.module.admin.entity.sys.SysConfig;
import com.bohuikeji.frame.module.admin.entity.sys.SysError;
import com.bohuikeji.frame.module.admin.entity.vo.AliReturnPayVo;
import com.bohuikeji.frame.module.admin.service.ISysConfigService;
import com.bohuikeji.frame.module.admin.utils.NumberUtils;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;

/**
 * <p>
 * 派送员入驻缴费记录 服务实现类
 * </p>
 *
 * @author 10552
 * @since 2019-12-27
 */
@Service
@Slf4j
public class TCourierPayServiceImpl extends ServiceImplBase<TCourierPayMapper, TCourierPay> implements ITCourierPayService {

    @Autowired
    ITCourierPayService courierPayService;
    @Autowired
    ITCourierService courierService;
    @Autowired
    ISysConfigService sysConfigService;
    @Autowired
    MqTool mqTool;

    /**
     * 入住缴费创建预支付单
     * @param playerId
     * @param price
     * @param payWay
     * @param scenario
     * @return
     */
    @Override
    public TCourierPay courierCreatePay(Integer playerId,String price,String payWay, String scenario) {
        TCourierPay pay=new TCourierPay();
        pay.setPayStatus("待付款");
        pay.setPlayerId(playerId);
        pay.setPayNum(NumberUtils.get("C"));
        pay.setPayExpectPrice(new BigDecimal(price));
        pay.setCreateTime(LocalDateTime.now());
        pay.setPayScenario(scenario);
        pay.setPayWay(payWay);
        if(save(pay)){
            mqTool.sendDelayMsg(pay.getPayNum(), PayTimoutListener.class, Duration.ofHours(3));
            return pay;
        }
        else {
            log.error("【数据库写入失败：】骑手入驻缴费——创建预付款订单失败，订单对象：{}",pay);
            SysError.saveError("骑手入驻缴费——创建预付款订单失败，订单对象：{0}",pay);
            throw new RuntimeException("【数据库写入失败：】骑手入驻缴费——创建预付款订单失败");
        }
    }

    /**
     * 微信&支付宝入驻缴费回调，业务处理
     * @param req
     * @param tCourierPay
     * @param jsonObject
     * @return
     */
    @Override
    public boolean updateCourierPay(AliReturnPayVo req,TCourierPay tCourierPay,JSONObject jsonObject) {
        TCourier courier = courierService.getById(tCourierPay.getPlayerId());
        if(courier == null){
            log.error("派送员信息不存在，请重新登陆");
            return false;
        }
        if("支付宝".equals(tCourierPay.getPayWay()) && StringUtils.isNotBlank(req.toString())){
            log.info("**************************入住缴费回调处理进入支付宝业务处理模块************************");
            tCourierPay.setPayFactPrice(new BigDecimal(req.getTotal_amount()));
            tCourierPay.setPayChannel("支付宝");
            tCourierPay.setPayChannelNum(req.getTrade_no());
            tCourierPay.setPayStatus("已支付");
            tCourierPay.setPayWay("支付宝");
            tCourierPay.setPayTime(LocalDateTime.now());
        }
        if("微信".equals(tCourierPay.getPayWay()) && StringUtils.isNotBlank(jsonObject.toString())){
            log.info("**************************入住缴费回调处理进入微信业务处理模块************************");
            tCourierPay.setPayFactPrice(new BigDecimal(jsonObject.getJSONObject("amount").getString("total")).divide(new BigDecimal(100)));
            tCourierPay.setPayChannel("微信");
            tCourierPay.setPayChannelNum(jsonObject.getString("transaction_id"));
            tCourierPay.setPayStatus("已支付");
            tCourierPay.setPayWay("微信");
            tCourierPay.setPayTime(LocalDateTime.now());
        }
        if(courierPayService.updateById(tCourierPay)){
            log.info("**************************入住缴费回调处理进入等级匹配处理模块************************");
            courier.setCourierSettledMoney(courier.getCourierSettledMoney().add(tCourierPay.getPayFactPrice()));
            courier.setCourierPayStatus("已缴费");
            SysConfig sysConfig=sysConfigService.getOne(new QueryWrapper<SysConfig>().eq("config_group","cost_set").eq("config_data_one",courier.getCourierSettledMoney().intValue()));
            log.info("配送员缴纳入住费用等级:[{}]",sysConfig.getConfigDefault());
            courier.setGrade(Integer.valueOf(sysConfig.getConfigDefault()));
            courierService.updateById(courier);
        }
            return true;
    }
}
