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

import com.alipay.api.response.AlipayFundTransUniTransferResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.bohuikeji.delivery.backstage.entity.*;
import com.bohuikeji.delivery.backstage.mapper.TCourierWithdrawMapper;
import com.bohuikeji.delivery.backstage.pay.AliPay;
import com.bohuikeji.delivery.backstage.service.*;
import com.bohuikeji.frame.module.admin.base.ServiceImplBase;
import com.bohuikeji.frame.module.admin.entity.sys.SysUser;
import com.bohuikeji.frame.module.admin.utils.NumberUtils;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
import com.bohuikeji.frame.module.admin.utils.wx.wxPayUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
/**
 * 骑手钱包业务处理类
 * @author Admin
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TCourierWithdrawServiceImpl extends ServiceImplBase<TCourierWithdrawMapper, TCourierWithdraw> implements ITCourierWithdrawService {
    final ITOrderService orderService;
    final ITCourierService courierService;
    final ITCourierCardService cardService;
    @Autowired
    ITRewardPayService rewardPayService;
    @Autowired
    ITCourierWithdrawService courierWithdrawService;
    @Autowired
    ITStoreWalletService storeWalletService;
    @Autowired
    ITCourierWorkExamService courierWorkExamService;

    /**
     * 微信结算审核
     * @param withdraw
     * @param loginUser
     * @param num
     * @param price
     * @param payWay
     * @return
     * @throws Exception
     */
    @Override
    public TCourierWithdraw wechatWithdrawal(TCourierWithdraw withdraw, SysUser loginUser,String num,String price,String payWay) throws Exception {
        if(loginUser.getRoleId().equals(7)){
            withdraw.setFranAuditUser(loginUser.getUserName());
        }
        if(loginUser.getRoleId().equals(1)){
            TCourierCard card=cardService.getOne(new QueryWrapper<TCourierCard>().eq("card_num",num));
            String partnerTradeNo = NumberUtils.get("TX");
            String type;
            if("APP".equals(card.getBankType())){
                type = "APPCOUR";
            }else {
                type = "APPCOMP";
            }
            Map<String, String> rs = wxPayUtil.withdrawal(partnerTradeNo,num,new BigDecimal(price),"骑手钱包提现",type);
            //APPLETS:小程序  APPCOUR：骑手端
            //AlipayFundTransUniTransferResponse response= AliPay.transferToAlipay(withdraw.getWithdrawId()+"",price,courier.getCourierName(),num);
            if(rs.get("result_code").equals("SUCCESS") && rs.get("return_code").equals("SUCCESS")){
                withdraw.setPayNum(rs.get("payment_no"));
                withdraw.setPartnerTradeNo(rs.get("partner_trade_no"));
                withdraw.setPayDate(LocalDateTime.parse(rs.get("payment_time"), StringUtils.dataTimeFormat));
                //往下三行代码是新修改的
                //withdraw.setOriginalAmount(withdraw.getApplyAmount());
                withdraw.setApplyAmount(withdraw.getApplyAmount().subtract(new BigDecimal(price)));
                withdraw.setCashAmount(withdraw.getCashAmount().add(new BigDecimal(price)));
            }else {
                withdraw.setWithdrawState("申请失败");
                withdraw.setWithdrawExplain(rs.get("err_code_des"));
                updateById(withdraw);
                log.info("骑手微信结算转账失败原因:[{}]",rs.get("err_code_des"));
                return withdraw;
            }
            if(withdraw.getApplyAmount().compareTo(new BigDecimal("0.00")) == 0){
                withdraw.setWithdrawState("已提现");
                withdraw.setApplyAmount(withdraw.getCashAmount());
            }
            withdraw.setPlatformExam("已通过");
            withdraw.setPlatformAuditUser(loginUser.getUserName());
            //订单打赏记录修改
            List<TCourierWithdraw> tCourierWithdraws = courierWithdrawService.list(new QueryWrapper<TCourierWithdraw>().eq("withdraw_group",withdraw.getWithdrawGroup()));
            if(tCourierWithdraws.size()>1){
                this.updateBusiness(tCourierWithdraws);
            }
        }
        withdraw.setPayCard(num);
        withdraw.setRealityAmount(withdraw.getApplyAmount());
        withdraw.setPayWay(payWay);
        withdraw.setFranExam("已通过");
        updateById(withdraw);
        return withdraw;
    }

    /**
     * 支付宝结算转账
     * @param withdraw
     * @param loginUser
     * @param num
     * @param price
     * @param payWay
     * @return
     */
    @Override
    public TCourierWithdraw alipayWithdrawal(TCourierWithdraw withdraw, SysUser loginUser, String num, String price, String payWay) {
        TCourier courier=courierService.getById(withdraw.getCourierId());
        if(loginUser.getRoleId().equals(7)){
            withdraw.setFranAuditUser(loginUser.getUserName());
        }
        if(loginUser.getRoleId().equals(1)){
            AlipayFundTransUniTransferResponse response= AliPay.transferToAlipay(withdraw.getWithdrawId()+"",price,"派送员提现",num);
            if(response.isSuccess()){
                withdraw.setPayNum(response.getOrderId());
                withdraw.setPayDate(LocalDateTime.parse(response.getTransDate(),StringUtils.dataTimeFormat));
            }else {
                withdraw.setWithdrawState("申请失败");
                updateById(withdraw);
                log.info("骑手微信结算转账失败原因:[{}]",response);
                return withdraw;
            }
            withdraw.setWithdrawState("已提现");
            withdraw.setPlatformExam("已通过");
            withdraw.setPlatformAuditUser(loginUser.getUserName());
            //订单打赏记录修改
            List<TCourierWithdraw> tCourierWithdraws = courierWithdrawService.list(new QueryWrapper<TCourierWithdraw>().eq("withdraw_group",withdraw.getWithdrawGroup()));
            if(tCourierWithdraws.size()>1){
                this.updateBusiness(tCourierWithdraws);
            }
        }
        withdraw.setPayCard(num);
        withdraw.setRealityAmount(withdraw.getApplyAmount());
        withdraw.setPayWay(payWay);
        withdraw.setFranExam("已通过");
        updateById(withdraw);
        return withdraw;
    }

    /**
     *线下结算转账
     * @param withdraw
     * @param loginUser
     * @param num
     * @param price
     * @param payWay
     * @return
     */
    @Override
    public TCourierWithdraw offlineWithdrawal(TCourierWithdraw withdraw, SysUser loginUser, String num, String price, String payWay) {
        String[] orderIds=withdraw.getOrderIds().split(",");
        if(orderService.update(new UpdateWrapper<TOrder>().in("order_id",orderIds).set("courier_sett_status","已结算"))){
            if(loginUser.getRoleId().equals(7)){
                withdraw.setWithdrawState("审核中");
                withdraw.setFranAuditUser(loginUser.getUserName());
            }
            if(loginUser.getRoleId().equals(1)){
                withdraw.setWithdrawState("已提现");
                withdraw.setPlatformExam("已通过");
                withdraw.setPlatformAuditUser(loginUser.getUserName());
                //订单打赏记录修改
                List<TCourierWithdraw> tCourierWithdraws = courierWithdrawService.list(new QueryWrapper<TCourierWithdraw>().eq("withdraw_group",withdraw.getWithdrawGroup()));
                if(tCourierWithdraws.size()>1){
                    this.updateBusiness(tCourierWithdraws);
                }
            }
            withdraw.setFranExam("已通过");
            withdraw.setPayWay(payWay);
            withdraw.setPayNum(num);
            withdraw.setPayDate(LocalDateTime.now());
            withdraw.setRealityAmount(withdraw.getApplyAmount());
            withdraw.setPayCard("线下收款");
            updateById(withdraw);
        }
        return withdraw;
    }

    /**
     * 直接付款到骑手支付宝账户，并生成提现记录
     * @param price     付款金额
     * @param courierId 骑手ID
     * @return
     */
    @Override
    public TCourierWithdraw sendToAliPay(String desc,BigDecimal price, Integer courierId) {
        TCourierCard courierCard=cardService.getOne(new QueryWrapper<TCourierCard>()
                .eq("courier_id",courierId)
                .eq("card_bank","支付宝"),false);
        if (courierCard==null){
            log.error("【付款到骑手支付宝账户失败】，骑手：{}，尚未绑定支付宝账户。",price);
            throw new RuntimeException("付款到骑手支付宝账户失败，骑手未绑定支付宝账户");
        }
        TCourierWithdraw withdraw =new TCourierWithdraw();
        withdraw.setWithdrawDesc(desc);
        withdraw.setCourierId(courierId);
        withdraw.setCountAmount(price);
        withdraw.setApplyAmount(price);
        withdraw.setRealityAmount(price);
        withdraw.setAccOverDeduction(new BigDecimal("0.00"));
        withdraw.setWithdrawState("已提现");
        AlipayFundTransUniTransferResponse res= AliPay.transferToAlipay(NumberUtils.get(),price.setScale(1,BigDecimal.ROUND_DOWN).toString(),"派送员提现",courierCard.getCardNum());
        if(res!=null){
            if(res.isSuccess()){
                withdraw.setPayNum(res.getOrderId());
                withdraw.setPayDate(LocalDateTime.parse(res.getTransDate(),StringUtils.dataTimeFormat));
            }else {
                withdraw.setWithdrawState("付款失败");
                updateById(withdraw);
                log.error("【付款到支付宝帐户失败】{},{}",res.getSubMsg(),res.getSubMsg());
                throw new RuntimeException("付款到骑手支付宝账户失败，"+res.getSubMsg());
            }
        }
        save(withdraw);
        return withdraw;
    }

    @Override
    public TCourierWithdraw saveWithdraw(List<TOrder> orderList,TCourier courier,String codeNum) {
        //已完成订单总交易额
        BigDecimal allMoney=new BigDecimal("0.00").setScale(2, BigDecimal.ROUND_DOWN);
        //已完成订单收益交额
        BigDecimal applyMoney=new BigDecimal("0.00").setScale(2, BigDecimal.ROUND_DOWN);
        //取件/送件超时扣款金额
        BigDecimal deductionMoney=new BigDecimal("0.00").setScale(2, BigDecimal.ROUND_DOWN);
        int over=0;
        StringBuilder str=new StringBuilder();
        for(TOrder order:orderList){
            //累加实际支付金额
            allMoney=allMoney.add(order.getOrderFactPrice());
            applyMoney=applyMoney.add(order.getOrderCourierMoney());
            deductionMoney= deductionMoney.add(order.getOverDeduction());
            over=over+order.getTimeOut();
            str.append(order.getOrderId());
            str.append(",");
        }
        TCourierWithdraw cw=new TCourierWithdraw();
        cw.setWithdrawDesc("本次结算订单："+orderList.size()+"笔");
        cw.setCourierId(courier.getCourierId());
        cw.setOrderIds(str.toString());
        cw.setCountAmount(allMoney);
        cw.setAccOverDeduction(deductionMoney);
        cw.setAccTimeOut(over);
        cw.setCreateDate(LocalDateTime.now());
        //申请到账金额(收益金额)
        cw.setApplyAmount(applyMoney);
        cw.setRealityAmount(applyMoney);
        cw.setFranId(courier.getFranId());
        cw.setWithdrawType("订单");
        cw.setWithdrawGroup(codeNum);
        cw.insert();
        return cw;
    }

    @Override
    public boolean updateBusiness(List<TCourierWithdraw> tCourierWithdraws) {
        for(TCourierWithdraw courierWithdraw : tCourierWithdraws){
            if("打赏".equals(courierWithdraw.getWithdrawType())){
                String[] orderIds=courierWithdraw.getOrderIds().split(",");
                courierWithdraw.setWithdrawState("已提现");
                courierWithdraw.setFranExam("已通过");
                courierWithdraw.setPlatformExam("已通过");
                courierWithdrawService.updateById(courierWithdraw);
                rewardPayService.update(new UpdateWrapper<TRewardPay>().set("pay_status","已提现").in("reward_id",orderIds));
            }
            if("惩罚".equals(courierWithdraw.getWithdrawType())){
                if(storeWalletService.saveWallet(courierWithdraw)){
                    String[] orderIds=courierWithdraw.getOrderIds().split(",");
                    courierWithdraw.setWithdrawState("已提现");
                    courierWithdraw.setFranExam("已通过");
                    courierWithdraw.setPlatformExam("已通过");
                    courierWithdrawService.updateById(courierWithdraw);
                    courierWorkExamService.update(new UpdateWrapper<TCourierWorkExam>().set("examine_state","已惩罚").in("examine_id",orderIds));
                }
            }
            if("奖励".equals(courierWithdraw.getWithdrawType())){
                if(storeWalletService.saveWallet(courierWithdraw)){
                    String[] orderIds=courierWithdraw.getOrderIds().split(",");
                    courierWithdraw.setWithdrawState("已提现");
                    courierWithdraw.setFranExam("已通过");
                    courierWithdraw.setPlatformExam("已通过");
                    courierWithdrawService.updateById(courierWithdraw);
                    courierWorkExamService.update(new UpdateWrapper<TCourierWorkExam>().set("examine_state","已奖励").in("examine_id",orderIds));
                }
            }
        }
        return true;
    }

    @Override
    public boolean updateReject(List<TCourierWithdraw> tCourierWithdraws) {
        for(TCourierWithdraw courierWithdraw : tCourierWithdraws){
            if("打赏".equals(courierWithdraw.getWithdrawType())){
                String[] orderIds=courierWithdraw.getOrderIds().split(",");
                courierWithdraw.setWithdrawState("申请失败");
                courierWithdraw.setFranExam("申请失败");
                courierWithdraw.setPlatformExam("已驳回");
                courierWithdrawService.updateById(courierWithdraw);
                rewardPayService.update(new UpdateWrapper<TRewardPay>().set("pay_status","已支付").in("reward_id",orderIds));
            }
            if("惩罚".equals(courierWithdraw.getWithdrawType())){
                if(storeWalletService.saveWallet(courierWithdraw)){
                    String[] orderIds=courierWithdraw.getOrderIds().split(",");
                    courierWithdraw.setWithdrawState("申请失败");
                    courierWithdraw.setFranExam("申请失败");
                    courierWithdraw.setPlatformExam("已驳回");
                    courierWithdrawService.updateById(courierWithdraw);
                    courierWorkExamService.update(new UpdateWrapper<TCourierWorkExam>().set("examine_state","待惩罚").in("examine_id",orderIds));
                }
            }
            if("奖励".equals(courierWithdraw.getWithdrawType())){
                if(storeWalletService.saveWallet(courierWithdraw)){
                    String[] orderIds=courierWithdraw.getOrderIds().split(",");
                    courierWithdraw.setWithdrawState("申请失败");
                    courierWithdraw.setFranExam("申请失败");
                    courierWithdraw.setPlatformExam("已驳回");
                    courierWithdrawService.updateById(courierWithdraw);
                    courierWorkExamService.update(new UpdateWrapper<TCourierWorkExam>().set("examine_state","待奖励").in("examine_id",orderIds));
                }
            }
        }
        return true;
    }
}
