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.entity.*;
import com.bohuikeji.delivery.backstage.listener.pay.PayTimoutListener;
import com.bohuikeji.delivery.backstage.mapper.TRewardPayMapper;
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.SysRes;
import com.bohuikeji.frame.module.admin.utils.NumberUtils;
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;
import java.util.List;

/**
 * <p>
 * 支付交易信息表 服务实现类
 * </p>
 *
 * @author 10552
 * @since 2019-12-27
 */
@Service
@Slf4j
public class TRewardPayServiceImpl extends ServiceImplBase<TRewardPayMapper, TRewardPay> implements ITRewardPayService {

    @Autowired
    ITOrderService orderService;
    @Autowired
    ITRewardPayService rewardPayService;
    @Autowired
    ITCourierService courierService;
    @Autowired
    ITLogisticsService logisticsService;
    @Autowired
    ITRefundService refundService;
    @Autowired
    ITEvaluateService evaluateService;
    @Autowired
    MqTool mqTool;


    /**
     *创建订单打赏预支付记录
     * @return
     */
    @Override
    public TRewardPay createRewardPay(TOrder order,String price,String scenario,String payMethod,String payWay,Integer serviceNum,Integer speedNum) {
        TRewardPay rewardPay=new TRewardPay();
        rewardPay.setPayStatus("待付款");
        rewardPay.setPlayerId(order.getPlayerId());
        rewardPay.setPayNum(NumberUtils.get("C"));
        rewardPay.setOrderId(order.getOrderId());
        rewardPay.setCourierId(order.getCourierId());
        rewardPay.setMerchantNum(order.getOrderNum());
        rewardPay.setRewardPrice(new BigDecimal(price));
        rewardPay.setCreateTime(LocalDateTime.now());
        rewardPay.setPayScenario(scenario);
        rewardPay.setPayMethod(payMethod);
        rewardPay.setPayWay(payWay);
        rewardPay.setServiceNum(serviceNum);
        rewardPay.setSpeedNum(speedNum);
        this.save(rewardPay);
        mqTool.sendDelayMsg(rewardPay.getPayNum(), PayTimoutListener.class, Duration.ofHours(3));
        return rewardPay;
    }


    /**
     * 订单打赏回调业务
     * @param jsonObject
     * @param rewardPay
     * @return
     */
    @Override
    public TRewardPay wxRewardPay(JSONObject jsonObject,TRewardPay rewardPay) {
        log.info("进入微信回调业务处理");
        //rewardPay.setRewardPrice(new BigDecimal(jsonObject.getJSONObject("amount").getString("payer_total")).divide(new BigDecimal(100)));//获取微信支付金额由分转成元/真鸡儿啰嗦
        rewardPay.setPayChannel("微信");
        rewardPay.setPayChannelNum(jsonObject.getString("transaction_id"));
        rewardPay.setPayStatus("已支付");
        rewardPay.setPayWay("微信");
        rewardPay.setPayTime(LocalDateTime.now());
        rewardPayService.updateById(rewardPay);
        if(rewardPayService.updateById(rewardPay)){
            TOrder order=orderService.getOne(new QueryWrapper<TOrder>().eq("evaluate_status","待评价").eq("order_id",rewardPay.getOrderId()));
            if(rewardPay.getServiceNum() != null && rewardPay.getSpeedNum() != null){
                TEvaluate tEvaluate=null;
                log.info("####################################################################");
                tEvaluate = evaluateService.setCustomer(order.getOrderId(),order.getPlayerId());
                tEvaluate.setEvaluateScore(evaluateService.setIntegral(tEvaluate.getEvaluateId(),rewardPay.getServiceNum(),rewardPay.getSpeedNum()));
                TCourier tCourier = courierService.getOne(new QueryWrapper<TCourier>().eq("courier_id",tEvaluate.getEvaluatedPersonId()));
                if(evaluateService.updateById(tEvaluate)){
                    order.setOrderReward(rewardPay.getRewardPrice());
                    order.setEvaluateStatus("已评价");
                    //TOrder tOrder = orderService.extractExtract(order);
                    orderService.updateById(order);
                }
                Double a=evaluateService.getObj(new QueryWrapper<TEvaluate>().select("AVG(evaluate_score)").eq("evaluated_person_id",order.getCourierId()),e->{
                    return Double.valueOf(e.toString());
                });
                //Integer num = tEvaluate.sql().selectCount("SELECT AVG(evaluate_score) FROM t_evaluate");
                log.info("评价分数:[{}]",a);
                Double summ = a/10.0;
                courierService.updateById(tCourier.setEvaluateScore(summ));
            }
        }
        log.info("订单打赏支付记录信息："+rewardPay);
        return rewardPay;
    }

    @Override
    public Object RewardCount(TCourier courier,String codeNum) {
        List<TRewardPay> rewardPays = rewardPayService.list(new QueryWrapper<TRewardPay>().eq("pay_status","已支付").eq("courier_id",courier.getCourierId()));
        Object RewardCount=0;
        if(rewardPays.size()>0){
            SysRes res=new SysRes();
            StringBuilder sss=new StringBuilder();
            RewardCount=res.sql().selectObj("select IFNULL(sum(reward_price),0) as sumc from t_reward_pay where courier_id={0} and pay_status='已支付'",courier.getCourierId());
            for(TRewardPay rewardPay : rewardPays){
                sss.append(rewardPay.getRewardId());
                sss.append(",");
            }
            TCourierWithdraw cw=new TCourierWithdraw();
            cw.setWithdrawDesc("本次打赏结算："+rewardPays.size()+"笔");
            cw.setCourierId(courier.getCourierId());
            cw.setOrderIds(sss.toString());
            cw.setCountAmount(new BigDecimal(RewardCount.toString()));
            //cw.setAccOverDeduction(deductionMoney);
            //cw.setAccTimeOut(over);
            cw.setCreateDate(LocalDateTime.now());
            //申请到账金额(收益金额)
            cw.setApplyAmount(new BigDecimal(RewardCount.toString()));
            cw.setRealityAmount(new BigDecimal(RewardCount.toString()));
            cw.setFranId(courier.getFranId());
            cw.setWithdrawType("打赏");
            cw.setWithdrawGroup(codeNum);
            cw.insert();
        }
        return RewardCount;
    }


}
