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


import com.alibaba.fastjson.JSONObject;
import com.alipay.api.response.AlipayFundTransUniTransferResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bohuikeji.delivery.backstage.entity.*;
import com.bohuikeji.delivery.backstage.entity.wx.TWxUser;
import com.bohuikeji.delivery.backstage.mapper.TWxtransfersMapper;
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.utils.NumberUtils;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
import com.bohuikeji.frame.module.admin.utils.wx.wxPayUtil;
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;


/**
 * <p>
 * 支付交易信息表 服务实现类
 * </p>
 *
 * @author 10552
 * @since 2019-12-27
 */
@Service
@Slf4j
public class TWxtransfersServiceImpl extends ServiceImplBase<TWxtransfersMapper, TWxtransfers> implements ITwxtransfersService {
    @Autowired
    ITwxtransfersService twxtransfersService;
    @Autowired
    ITCustomerWalletService customerWalletService;
    @Autowired
    ITwalletDetailService twalletDetailService;
    @Autowired
    ITCustomerPayService customerPayService;
    @Autowired
    ITGiveDetailService giveDetailService;
    @Autowired
    IWxUserService wxUserService;

    @Override
    public TWxtransfers createTransters(TCustomerWallet tCustomerWallet){
        TWxtransfers tWxtransfers = new TWxtransfers();
        tWxtransfers.setWalletId(tCustomerWallet.getWalletId());
        tWxtransfers.setPartnerNum(NumberUtils.get("TX"));
        tWxtransfers.setTransfersWay("微信提现");
        tWxtransfers.setTransfersPrice(tCustomerWallet.getRefuntPrice());
        tWxtransfers.setCreateTime(LocalDateTime.now());
        tWxtransfers.setTransfersState("提现中");
        twxtransfersService.save(tWxtransfers);
        return tWxtransfers;
    }

    @Override
    public JSONObject wXAndAliWithdrawal(String type,TCustomerWallet tCustomerWallet,TCustomer tCustomer) {
        String msg=null;
        JSONObject jsonObject = new JSONObject();
        TWxtransfers tWxtransfers = twxtransfersService.createTransters(tCustomerWallet);
        if("微信".equals(type)){
            wxPayUtil payUtil = new wxPayUtil();
            String openId = null;
            String types = null;
            if(StringUtils.isNotBlank(tCustomer.getCustAppOpenId())){
                openId = tCustomer.getCustAppOpenId();
                types  = "APPCUST";//客户端App提现
            }else {
                openId = tCustomer.getOpenId();
                types  = "APPLETS";//小程序提现
            }
            Map<String, String> rs = payUtil.withdrawal(tWxtransfers.getPartnerNum(),openId,tWxtransfers.getTransfersPrice(),"客户钱包余额提现",types);
            if(rs.get("result_code").equals("SUCCESS") && rs.get("return_code").equals("SUCCESS")){
                this.updateWalletAndTransfers(type,tWxtransfers,tCustomerWallet,tCustomer,rs,null);
                jsonObject.put("success","SUCCESS");
            }else {
                tWxtransfers.setPlayerId(tCustomer.getCustomerId());
                tWxtransfers.setFranId(tCustomerWallet.getFranId());
                tWxtransfers.setPaymentTime(LocalDateTime.now());
                tWxtransfers.setTransfersState("付款失败");
                tWxtransfers.setTransfersChannel("微信");
                tWxtransfers.setPaymentNum(rs.get("err_code_des"));
                twxtransfersService.updateById(tWxtransfers);
                jsonObject.put("fail",rs.get("err_code_des"));
            }
        }
        if("支付宝".equals(type)){
            TWxUser wxUser = wxUserService.getOne(new QueryWrapper<TWxUser>().eq("user_id",tCustomer.getCustomerId()).eq("wx_app_type","ALICLIENT"));
            AlipayFundTransUniTransferResponse res= AliPay.transferToAlipay(tWxtransfers.getPartnerNum(),tWxtransfers.getTransfersPrice().setScale(1,BigDecimal.ROUND_DOWN).toString(),"钱包余额提现",wxUser.getWxUserOpenid());
            if(res!=null && res.isSuccess()){
                this.updateWalletAndTransfers(type,tWxtransfers,tCustomerWallet,tCustomer,null,res);
                jsonObject.put("success","SUCCESS");
            }else {
                tWxtransfers.setPlayerId(tCustomer.getCustomerId());
                tWxtransfers.setFranId(tCustomerWallet.getFranId());
                tWxtransfers.setPaymentTime(LocalDateTime.now());
                tWxtransfers.setTransfersState("付款失败");
                tWxtransfers.setTransfersChannel("支付宝");
                tWxtransfers.setPaymentNum(res.getMsg());
                twxtransfersService.updateById(tWxtransfers);
                jsonObject.put("fail",res.getMsg());
            }
        }
        this.updateGivePirce(tCustomerWallet);//更改充值赠送金额
        return jsonObject;
    }

    /**
     * 更改充值赠送金额
     * @param tCustomerWallet
     */
    @Override
    public void updateGivePirce(TCustomerWallet tCustomerWallet) {
        List<TGiveDetail> giveDetails = giveDetailService.list(new QueryWrapper<TGiveDetail>().eq("customer_id",tCustomerWallet.getCustomerId()).eq("give_status","未使用"));
        for(TGiveDetail giveDetail : giveDetails){
            giveDetail.setGiveStatus("已使用");
            giveDetail.setUpdateTime(LocalDateTime.now());
            giveDetailService.updateById(giveDetail);
        }
    }

    /**
     * 更改钱包信息
     * @param type
     * @param tWxtransfers
     * @param tCustomerWallet
     * @param tCustomer
     * @param rs
     * @param res
     */
    @Override
    public void updateWalletAndTransfers(String type,TWxtransfers tWxtransfers,TCustomerWallet tCustomerWallet,TCustomer tCustomer,Map<String, String> rs, AlipayFundTransUniTransferResponse res) {
        if(rs !=null && rs.get("result_code").equals("SUCCESS")){
            tWxtransfers.setPartnerNum(rs.get("partner_trade_no"));
            tWxtransfers.setPaymentNum(rs.get("payment_no"));
        }
        if(res != null && res.isSuccess()){
            log.info("支付宝提现：",res);
            tWxtransfers.setPartnerNum(res.getOrderId());
            tWxtransfers.setPaymentNum(res.getPayFundOrderId());
        }
        tWxtransfers.setWalletId(tWxtransfers.getWalletId());
        tWxtransfers.setTransfersChannel(type);
        tWxtransfers.setPlayerId(tCustomer.getCustomerId());
        tWxtransfers.setFranId(tCustomerWallet.getFranId());
        tWxtransfers.setPaymentTime(LocalDateTime.now());
        tWxtransfers.setTransfersState("付款成功");
        if(twxtransfersService.updateById(tWxtransfers)){
            tCustomerWallet.setWalletState("提现");
            tCustomerWallet.setRefuntPrice(new BigDecimal(0));
            tCustomerWallet.setPreferPrice(new BigDecimal(0));
        }
        if(customerWalletService.updateById(tCustomerWallet)){
            twalletDetailService.saveDetail(null,null,tWxtransfers,tCustomerWallet,"余额提现");
        }

    }


}
