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

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bohuikeji.delivery.backstage.entity.TOrder;
import com.bohuikeji.delivery.backstage.entity.TPay;
import com.bohuikeji.delivery.backstage.entity.TRefund;
import com.bohuikeji.delivery.backstage.service.ITOrderService;
import com.bohuikeji.delivery.backstage.service.ITPayService;
import com.bohuikeji.delivery.backstage.service.ITRefundService;
import com.bohuikeji.frame.module.admin.annotation.InitLog;
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.SysUser;
import com.bohuikeji.frame.module.admin.service.ISysConfigService;
import com.bohuikeji.frame.module.admin.service.ISysUserService;
import com.bohuikeji.frame.module.admin.utils.JwtTokenUtil;
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.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;

@Api(tags = {"管理端APP接口——取消订单"})
@RestController
@RequestMapping("/api/cancel")
@Slf4j
public class AdminPayApi {

    @Autowired
    ITOrderService itOrderService;
    @Autowired
    ITPayService payService;
    @Autowired
    ITRefundService refundService;

    /**
     *管理端App退款
     * @param
     * @return
     * @throws AlipayApiException
     * @throws IOException
     */
    @InitLog(value = "管理端App退款",action = "退款")
    @ApiOperation("管理端App退款")
    @GetMapping("/order/Refund")
    public APIEntity orderRefund(Integer orderId){
        TOrder tOrder = itOrderService.getById(orderId);
        if(tOrder==null){
            return APIEntity.fail("退款订单不存在");
        }
        TRefund refund=null;
        List<TPay> tPays = payService.list(new QueryWrapper<TPay>().eq("order_id",tOrder.getOrderId()).eq("pay_status","已支付"));
        if(tPays.size() < 1){
            return APIEntity.success("该订单没有支付记录，请检查是否支付");
        }
        if(tPays.size() > 0){
            refundService.cancel(tOrder,tPays);
            itOrderService.cancelOrder("系统已为您退款，如有疑问请联系客服",tOrder);
        }
        return APIEntity.success(refund);
    }

}
