package com.bohuikeji.delivery.backstage.controller.api.pay;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.StreamUtil;
import com.alipay.api.response.AlipayTradeCancelResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
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.listener.pay.AliPayListener;
import com.bohuikeji.delivery.backstage.pay.AliPay;
import com.bohuikeji.delivery.backstage.service.*;
import com.bohuikeji.frame.module.admin.base.ApiController;
import com.bohuikeji.frame.module.admin.component.MqTool;
import com.bohuikeji.frame.module.admin.entity.back.APIEntity;
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 com.bohuikeji.frame.module.admin.utils.wx.wxPayUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;



/**
 * @author zhouliwu
 * 支付相关接口
 * 注：所以接口类必须继承 ApiController，否则无法被接口文档识别
 */
@Api(tags = {"微信支付宝支付相关接口"})
@RestController
@RequestMapping("/api/aliPay")
@Slf4j
public class AliPayApi extends ApiController {
    @Autowired
    ITOrderService itOrderService;
    @Autowired
    ITPayService payService;
    @Autowired
    ITCourierPayService courierPayService;
    @Autowired
    ITCustomerWalletService customerWalletService;
    @Autowired
    ITCustomerPayService customerPayService;
    @Autowired
    ITRefundService refundService;
    @Autowired
    ITCourierService courierService;
    @Autowired
    ISysConfigService configService;
    @Autowired
    ITCustomerService customerService;
    @Autowired
    MqTool mqTool;


    /**
     * 派送员缴纳入驻费用
     * @param id
     * @return
     * @throws AlipayApiException
     */
    @ApiOperation("派送员缴纳入驻费用")
    @PostMapping("/aliCourierPay")
    public APIEntity aliCourierPay(@ApiIgnore @RequestAttribute("JwtUserId") Integer id){
        TCourier courier = courierService.getById(id);
        if (courier == null) {
            return APIEntity.fail("无法找到骑手信息，请重新登陆！", 412);
        }
        TCourierPay oldPay = courierPayService.getOne(new QueryWrapper<TCourierPay>().eq("player_id", id).in("pay_status","已支付","待付款"));
        //如果有已支付的订单则提示用户刷新客户端
        if(oldPay!=null){
            if("已支付".equals(oldPay.getPayStatus())){
                courierService.update(new UpdateWrapper<TCourier>().set("courier_pay_status", "已缴费").eq("courier_id", id));
                return APIEntity.fail("您已经支付过了，请重新打开APP再试！");
            }
            if("待付款".equals(oldPay.getPayStatus())){
                courierPayService.updateById(oldPay.setPayWay("支付宝"));
                String rs = AliPay.aliAppPay(oldPay.getPayNum(), courierService.getCourierPrice(id).getConfigValue());
                return rs==null?APIEntity.fail("获取支付宝预支付错误！"):APIEntity.success(rs);
            }
        }
        //获取预付款TPay对象
        TCourierPay beforePay = courierPayService.courierCreatePay(id, courierService.getCourierPrice(id).getConfigValue(), "支付宝","入驻缴费");
        String rs = AliPay.aliAppPay(beforePay.getPayNum(), beforePay.getPayExpectPrice().toString());
        return rs==null?APIEntity.fail("获取支付宝预支付错误！"):APIEntity.success(rs);

    }

    /**
     * 派送员根据缴费等级计算充值金额
     * @param id
     * @return
     * @throws AlipayApiException
     */
    @ApiOperation("派送员根据缴费等级计算充值金额")
    @GetMapping("/calculationRecharge")
    @ApiImplicitParams({
            @ApiImplicitParam(name="configId",value="缴费等级id",dataType="Integer", paramType = "query",example="1",required = true)})
    public APIEntity calculationRecharge(@ApiIgnore @RequestAttribute("JwtUserId") Integer id,Integer configId){
        TCourier courier = courierService.getById(id);
        if (courier == null) {
            return APIEntity.fail("无法找到骑手信息，请重新登陆！", 412);
        }
        SysConfig sysConfig = configService.getById(configId);
        if(new BigDecimal(Integer.parseInt(sysConfig.getConfigDataOne())).compareTo(courier.getCourierSettledMoney()) == 0){
            return APIEntity.success(courier.getCourierSettledMoney());
        }
        if(new BigDecimal(Integer.parseInt(sysConfig.getConfigDataOne())).compareTo(courier.getCourierSettledMoney()) > 0){
            BigDecimal price = new BigDecimal(Integer.parseInt(sysConfig.getConfigDataOne())).subtract(courier.getCourierSettledMoney());
            return APIEntity.success(price);
        }else {
            BigDecimal price = new BigDecimal("0.00");
            return APIEntity.success(price);
        }
    }


    /**
     * 派送员根据等级缴纳入驻费用
     * @param id
     * @return
     * @throws AlipayApiException
     */
    @ApiOperation("派送员根据等级缴纳入驻费用")
    @GetMapping("/aliCourierRecharge")
    public APIEntity courierRecharge(@ApiIgnore @RequestAttribute("JwtUserId") Integer id,String price){
        TCourier courier = courierService.getById(id);
        if (courier == null) {
            return APIEntity.fail("无法找到骑手信息，请重新登陆！", 412);
        }
        SysConfig sysConfig=configService.getOne(new QueryWrapper<SysConfig>().eq("config_group","cost_set").eq("config_data_one",courier.getCourierSettledMoney().add(new BigDecimal(price))));
        if(StringUtils.isBlank(sysConfig.toString())){
            log.error("当前缴纳费用没有相应的匹配等级，缴纳费用:[{}]",courier.getCourierSettledMoney().intValue());
            SysError.saveError("当前缴纳费用没有相应的匹配等级，骑手入驻支付单：{0}元，{1}",courier.getCourierSettledMoney().intValue(),courier.getCourierName());
            return APIEntity.fail("当前缴纳费用没有相应的匹配等级,如有疑问请联系客服！", 412);
        }
        TCourierPay oldPay = courierPayService.getOne(new QueryWrapper<TCourierPay>().eq("player_id", id).eq("pay_way","支付宝").in("pay_status","待付款"));
        log.info("!!!!!!!!!!!!!支付宝预支付订单信息：[{}]",oldPay);
        //如果有已支付的订单则提示用户刷新客户端
        if(oldPay!=null){
                String rs = AliPay.aliAppPay(oldPay.getPayNum(), oldPay.getPayExpectPrice().toString());
                return rs==null?APIEntity.fail("获取支付宝预支付错误！"):APIEntity.success(rs);
        }
        //获取预付款TPay对象
        TCourierPay beforePay = courierPayService.courierCreatePay(id, price, "支付宝","入驻缴费");
        String rs = AliPay.aliAppPay(beforePay.getPayNum(), beforePay.getPayExpectPrice().toString());
        return rs==null?APIEntity.fail("获取支付宝预支付错误！"):APIEntity.success(rs);

    }

    /**
     * 支付宝支付（骑手代缴）
     * @param id
     * @param orderId
     * @param price
     * @return
     */
    @ApiOperation("支付宝支付（骑手代缴）")
    @GetMapping("/courier/payment")
    public APIEntity courierPayment(@ApiIgnore @RequestAttribute("JwtUserId") Integer id,Integer orderId,String price){
        if(!StringUtils.isPrice(price)){
            return APIEntity.fail("无法识别订单金额，请检查格式是否正确！！");
        }
        log.info("参数：[{}],[{}]",id,orderId);
        TOrder order=itOrderService.getById(orderId);
        if(order==null){
            log.error("未找到该订单信息");
            return APIEntity.fail("未找到该订单信息！");
        }
        if(order.getCourierId()==null){
            log.error("【派送员订单代缴接口异常】，无法找到派送员信息！");
            SysError.saveError("【派送员订单代缴接口异常】，无法找到派送员信息！，当前订单实体={0}",order);
            return APIEntity.fail("无法找到派送员信息，请尝试重新登陆或者，联系平台核实！");
        }
        if(!order.getCourierId().equals(id)){
            log.error("订单与派送员不批配，无法完成支付");
            return APIEntity.fail("订单与派送员不批配，无法完成支付");
        }
        TPay pay = payService.getOne(new QueryWrapper<TPay>().eq("order_id",order.getOrderId()).in("pay_status","待付款"));
        log.info("派送员代缴，支付记录的查询:[{}]",pay);
        if (pay!=null){
            if("待付款".equals(pay.getPayStatus())){
                String rs = AliPay.aliAppPay(pay.getPayNum(), price);
                return rs==null?APIEntity.fail("获取支付宝预支付错误！"):APIEntity.success(rs);
            }
        }
        String rs = null;
        if("取件中".equals(order.getOrderStatus())){
            pay =payService.createBeforePay(order,"补充支付","骑手代付","支付宝APP");
            rs = AliPay.aliAppPay(pay.getPayNum(), price);
        }
        return rs==null?APIEntity.fail("获取支付宝预支付错误！"):APIEntity.success(rs);
    }

    /**
     * 客户钱包充值缴费缴费
     * @param id
     * @return
     * @throws AlipayApiException
     */
    @ApiOperation("客户钱包充值缴费缴费")
    @GetMapping("/alipay/wallet")
    public APIEntity alipayWallet(@ApiIgnore @RequestAttribute("JwtUserId") Integer id,String price,String location){
        TCustomer customer = customerService.getById(id);
        if (customer == null) {
            return APIEntity.fail("无法找到客户信息，请重新登陆！", 412);
        }
        TCustomerWallet tCustomerWallet = customerWalletService.getOne(new QueryWrapper<TCustomerWallet>().eq("customer_id",customer.getCustomerId()).eq("wallet_state","提现中"));
        if(tCustomerWallet != null){
            return APIEntity.fail("您的钱包余额正在提现中，请稍候充值。");
        }
        TCustomerPay customerPay = customerPayService.getOne(new QueryWrapper<TCustomerPay>().eq("player_id",customer.getCustomerId()).eq("pay_status","待付款"));
        if(customerPay != null){
            if("待付款".equals(customerPay.getPayStatus())){
                customerPay.setPayExpectPrice(new BigDecimal(price));
                customerPay.setPayWay("支付宝");
                customerPayService.updateById(customerPay);
                String rs = AliPay.aliAppPay(customerPay.getPayNum(), price);
                return rs==null?APIEntity.fail("获取支付宝预支付错误！"):APIEntity.success(rs);
            }
        }
        //获取预付款TPay对象
        TCustomerPay tCustomerPay = customerPayService.createWalletPay(customer, price, "支付宝","钱包充值",location);
        String rs = AliPay.aliAppPay(tCustomerPay.getPayNum(), tCustomerPay.getPayExpectPrice().toString());
        return rs==null?APIEntity.fail("获取支付宝预支付错误！"):APIEntity.success(rs);

    }

    /**
     *支付宝订单业务退款接口
     * @param
     * @return
     * @throws AlipayApiException
     * @throws IOException
     */
    @ApiOperation("支付宝订单业务退款接口")
    @PostMapping("/aliRefund")
    public APIEntity aliRefund(Integer orderId){
        TOrder tOrder = itOrderService.getById(orderId);
        TPay tPay = payService.getOne(new QueryWrapper<TPay>().eq("order_id",tOrder.getOrderId()));
        if(tOrder == null){
            return APIEntity.fail("该订单不存在");
        }
        if(tPay == null){
            return APIEntity.fail("该订单支付信息不存在");
        }
        TRefund refund=null;
        AlipayTradeRefundResponse response = AliPay.refund(tOrder.getOrderNum(),tOrder.getOrderFactPrice().toString(),tPay.getPayChannelNum(),tOrder.getRefundReason(),String.valueOf(System.currentTimeMillis()));
        if(!"10000".equals(response.getCode())){
            log.info("业务处理错误！ "+response.getSubMsg());
            return APIEntity.fail(response.getSubMsg());
        }
        if("Y".equals(response.getFundChange())){
            refund = refundService.wxAltRefund(null,response,null,null,null,tOrder,tPay,null,"业务订单退款");
        }
        return APIEntity.success(refund);
    }

    /**
     *支付宝派送员退款接口
     * @param
     * @return
     * @throws AlipayApiException
     * @throws IOException
     */
    /*@ApiOperation("支付宝派送员退款接口")
    @PostMapping("/aliCourierRefund")
    public APIEntity aliCourierRefund(@ApiIgnore @RequestAttribute("JwtUserId") Integer id){

        //return APIEntity.fail("您好，退款功能正在维护中，暂停使用……");

        TCourier  courier = courierService.getById(id);
        if(courier == null){
            return APIEntity.fail("未找到骑手信息，请重新登陆。").setStatus(412);
        }
        List<TCourierPay> payList=courierPayService.list(new QueryWrapper<TCourierPay>().eq("player_id",id).eq("pay_scenario","入驻缴费").eq("pay_status","已支付"));
        if(payList==null||payList.size()==0){
            return APIEntity.fail("没有找到您的订单信息！");
        }
        if(payList.size()>1){
            return APIEntity.fail("您的支付订单异常，请联系客服处理");
        }
        if(itOrderService.list(new QueryWrapper<TOrder>().eq("courier_id",id).in("order_status","待取件","取件中","待派送","派送中")).size()>0){
            return APIEntity.fail("您有正在进行中的订单，无法退款，请先完成订单~");
        }
        TRefund refund=refundService.ettlecCancel(payList,courier);
        return APIEntity.success(refund);
    }*/


    /**
     * 支付宝支付订单查询
     * @param orderId
     * @return
     */
    @ApiOperation("支付订单查询接口")
    @PostMapping("/getPay")
    public APIEntity aliPay(Integer orderId){
        TOrder tOrder = itOrderService.getById(orderId);
        TPay tPay = payService.getOne(new QueryWrapper<TPay>().eq("order_id",tOrder.getOrderId()));
        AlipayTradeQueryResponse response = AliPay.aliQuery(tOrder.getOrderNum(),tPay.getPayChannelNum());
        if(!"10000".equals(response.getCode())){
            return APIEntity.fail(response.getSubMsg());
        }
        return APIEntity.success(response);
    }

    /**
     * 支付宝撤销订单接口
     * @param orderId
     * @return
     */
    @ApiOperation("撤销订单接口")
    @PostMapping("/getPayCancel")
    public APIEntity aliPayCancel(Integer orderId){
        TOrder tOrder = itOrderService.getById(orderId);
        TPay tPay = payService.getOne(new QueryWrapper<TPay>().eq("order_id",tOrder.getOrderId()));
        AlipayTradeCancelResponse response = AliPay.aliCancel(tOrder.getOrderNum(),tPay.getPayChannelNum());
        if(!"10000".equals(response.getCode())){
            return APIEntity.fail(response.getSubMsg());
        }
        return APIEntity.success(response);
    }

    /**
     * 支付宝回调的接口
     *
     * @return
     * @throws IOException
     */
    @ApiOperation("支付宝支付异步回调")
    @PostMapping("/notify")
    public String returnPay(AliReturnPayVo req,HttpServletRequest request, HttpServletResponse response) throws IOException {
        String str = StreamUtil.readText(request.getInputStream());
        JSONObject strjson= JSONObject.parseObject(str);
        log.error("#############################：{}",strjson);
        log.error("支付宝回掉进入：{}",req);
        //支付完成推送至消息队列
        mqTool.sendMsg(req, AliPayListener.class);
        return "success";
    }

    /**
     * 微信订单业务支付退款
     * @param orderId
     * @return
     */
    /*@ApiOperation("微信支付退款")
    @PostMapping("/payRefund")
    public APIEntity wxPayRefund(Integer orderId) {
        TOrder tOrder = itOrderService.getById(orderId);
        TPay tPay = payService.getOne(new QueryWrapper<TPay>().eq("order_id",tOrder.getOrderId()));
        if(tOrder == null){
            log.info("未找到该订单");
            return APIEntity.fail("该订单不存在");
        }
        TRefund refund= null;
        wxPayUtil payUtil = new wxPayUtil();
        *//*String SS = "T"+System.currentTimeMillis();*//*
        Map<String, String> rs = payUtil.refund(tOrder.getOrderNum(),NumberUtils.get("T"), tPay.getPayFactPrice().toString(),tPay.getPayFactPrice().toString(), "同城急送");
        log.info("微信付款码支付退款返回结果 [{}]",rs);
        if ("SUCCESS".equals(rs.get("result_code"))){
            refund = refundService.wxAltRefund(rs,null,null,null,null,tOrder,tPay,null,"业务订单退款");
            log.info("申请退款成功");
            return APIEntity.success(refund);
        } else {
            return APIEntity.fail(rs.get("result_code"));
        }
    }*/

}
