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.TCustomer;
import com.bohuikeji.delivery.backstage.entity.TCustomerPay;
import com.bohuikeji.delivery.backstage.entity.TCustomerWallet;
import com.bohuikeji.delivery.backstage.listener.pay.PayTimoutListener;
import com.bohuikeji.delivery.backstage.mapper.TCustomerPayMapper;
import com.bohuikeji.delivery.backstage.pay.AliPay;
import com.bohuikeji.delivery.backstage.pay.PayServices;
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.SysError;
import com.bohuikeji.frame.module.admin.entity.vo.AddressVo;
import com.bohuikeji.frame.module.admin.entity.vo.AliReturnPayVo;
import com.bohuikeji.frame.module.admin.service.ITFranchiseeInformationService;
import com.bohuikeji.frame.module.admin.utils.MapUtils;
import com.bohuikeji.frame.module.admin.utils.NumberUtils;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
import com.bohuikeji.frame.module.admin.wxpay.WXPayUtil;
import com.bohuikeji.frame.module.admin.wxpayv3.WxPayV3Util;
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-12-27
 */
@Service
@Slf4j
public class TCustomerPayServiceImpl extends ServiceImplBase<TCustomerPayMapper, TCustomerPay> implements ITCustomerPayService {

    @Autowired
    ITCustomerPayService customerPayService;
    @Autowired
    ITCustomerService customerService;
    @Autowired
    ITCustomerWalletService customerWalletService;
    @Autowired
    ITDiscountRecordService receiveRecordService;
    @Autowired
    ITFranchiseeInformationService franServer;
    @Autowired
    MqTool mqTool;

    /**
     * 客户钱包充值预支付订单
     * @param price
     * @param scenario
     * @return
     */
    @Override
    public TCustomerPay createWalletPay(TCustomer customer, String price, String payWay, String scenario,String location) {
        TCustomerPay customerPay=new TCustomerPay();
        Integer franId=null;
        if(StringUtils.isNotBlank(location)){
            AddressVo address = MapUtils.getAddressReGeo(location);
            franId = franServer.checkPio(address).getFranId();
        }else {
            franId = 1;
        }
        TCustomerWallet customerWallet = customerWalletService.getOne(new QueryWrapper<TCustomerWallet>().eq("customer_id",customer.getCustomerId()));
        if(customerWallet != null){
            customerPay.setWalletId(customerWallet.getWalletId());
            customerWallet.setFranId(franId);
            customerWallet.setCustomerPhone(customer.getCustomerPhone());
            customerWalletService.updateById(customerWallet);
        }else {
            TCustomerWallet tCustomerWallet = new TCustomerWallet();
            tCustomerWallet.setCustomerId(customer.getCustomerId());
            tCustomerWallet.setCustomerPhone(customer.getCustomerPhone());
            tCustomerWallet.setWalletState("提现");
            tCustomerWallet.setCreateTime(LocalDateTime.now());
            tCustomerWallet.setFranId(franId);
            customerWalletService.save(tCustomerWallet);
            customerPay.setWalletId(tCustomerWallet.getWalletId());
        }
        customerPay.setFranId(1);
        customerPay.setPayStatus("待付款");
        customerPay.setPlayerId(customer.getCustomerId());
        customerPay.setPayNum(NumberUtils.get("C"));
        customerPay.setPayExpectPrice(new BigDecimal(price));
        customerPay.setCreateTime(LocalDateTime.now());
        customerPay.setPayScenario(scenario);
        customerPay.setPayWay(payWay);
        if(save(customerPay)){
            mqTool.sendDelayMsg(customerPay.getPayNum(), PayTimoutListener.class, Duration.ofHours(3));
            return customerPay;
        }
        else {
            log.error("数据库写入失败：客户钱包充值——创建预支付订单失败，对象：{}",customerPay);
            SysError.saveError("客户钱包充值——创建预支付订单失败，支付单：{0}号已丢失",customerPay);
            throw new RuntimeException("【数据库写入失败：】客户钱包充值——创建预支付订单失败");
        }
    }

    @Override
    public JSONObject getCustomer(TCustomer customer, String price, String type, String payStatus, HttpServletRequest request) {
        String codeurl=null;
        JSONObject jsonObject = new JSONObject();
        TCustomerPay customerPay = customerPayService.getOne(new QueryWrapper<TCustomerPay>().eq("player_id",customer.getCustomerId()).eq("pay_status","待付款"));
        if(customerPay != null){
            customerPay.setPayExpectPrice(new BigDecimal(price));
            customerPay.setPayWay(type);
            customerPayService.updateById(customerPay);
        }else {
            customerPay = customerPayService.createWalletPay(customer, price, type, "钱包充值", null);
        }
        if("微信".equals(type)){
            try {
                codeurl = WxPayV3Util.V3Native(request,"v3/pay/transactions/native",customerPay.getPayNum(),new BigDecimal(WXPayUtil.changeToFen(new BigDecimal(price))),"钱包充值支付");
                jsonObject.put("codeurl",codeurl);
                jsonObject.put("logourl","https://oss.bhynm.com/delivery/upload/2022/3/29/164852323024812.jpg");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if("支付宝".equals(type)){
            codeurl = AliPay.alipayPrecreate(customerPay.getPayNum(),price,"钱包充值支付");
            jsonObject.put("codeurl",codeurl);
            jsonObject.put("logourl","https://oss.bhynm.com/delivery/upload/2022/3/29/164852304400549.jpg");
        }
        return jsonObject;
    }

    /**
     * 微信&支付宝钱包充值，业务处理
     * @param req
     * @param customerPay
     * @param jsonObject
     * @return
     */
    @Override
    public boolean updateWalletPay(AliReturnPayVo req, TCustomerPay customerPay, JSONObject jsonObject) {
        TCustomerWallet customerWallet = customerWalletService.getById(customerPay.getWalletId());
        if(customerWallet == null){
            log.error("客户信息不存在，请重新登陆");
            return false;
        }
        JSONObject js=null;
        if("微信".equals(customerPay.getPayWay())){
            log.info("微信充值返回参数：{}",jsonObject);
            if(StringUtils.isNotBlank(jsonObject.getString("promotion_detail"))){
                for (int i = 0; i < jsonObject.getJSONArray("promotion_detail").size(); i++) {
                    js = jsonObject.getJSONArray("promotion_detail").getJSONObject(i);
                }
            }
        }
        if(customerPayService.updateById(PayServices.getCustomerPaySrevice(jsonObject,req,customerPay))){
            customerWallet.setWalletPrice(customerWallet.getWalletPrice().add(customerPay.getPayExpectPrice()));
            customerWallet.setUpdateTime(LocalDateTime.now());
            if(js != null){//钱包微信充值时 记录优惠金额
                customerWallet.setPreferPrice(customerWallet.getPreferPrice().add(new BigDecimal(js.getString("amount")).divide(new BigDecimal("100"))));
            }
            if(req != null){//钱包支付宝充值时 记录优惠金额
                customerWallet.setPreferPrice(customerWallet.getPreferPrice().add(customerPay.getPayFactPrice().subtract(new BigDecimal(req.getReceipt_amount()))));

            }
            customerWalletService.updateById(customerWallet);
            return true;
        }
        return false;
    }
}
