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

import com.alipay.api.AlipayApiException;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bohuikeji.delivery.backstage.constants.KeyConst;
import com.bohuikeji.delivery.backstage.entity.*;
import com.bohuikeji.delivery.backstage.entity.vo.CourierAddressVo;
import com.bohuikeji.delivery.backstage.pay.AliPay;
import com.bohuikeji.delivery.backstage.service.*;
import com.bohuikeji.delivery.backstage.util.maiyatian.maltUtils;
import com.bohuikeji.frame.module.admin.annotation.InitLog;
import com.bohuikeji.frame.module.admin.base.ControllerBase;
import com.bohuikeji.frame.module.admin.component.RedisUtil;
import com.bohuikeji.frame.module.admin.entity.back.APIEntity;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
/**
 * 支付、退款业务
 */
@Slf4j
@Controller
@ResponseBody
@RequestMapping("/tpay")
public class TPayController extends ControllerBase {

    @Autowired
    ITOrderService itOrderService;
    @Autowired
    ITPayService payService;
    @Autowired
    ITCourierPayService courierPayService;
    @Autowired
    ITRefundService refundService;
    @Autowired
    ITNewsService newsService;
    @Autowired
    ITOrderExceptionService orderExceptionService;
    @Autowired
    ITCourierService courierService;
    @Autowired
    ITMaltFieldService maltFieldService;
    @Autowired
    RedisUtil redisUtil;

    @Autowired
    protected HttpSession session;


    /**
     *后台管理操作退款
     * @param
     * @return
     * @throws AlipayApiException
     * @throws IOException
     */
    @InitLog(value = "后台管理操作退款",action = "退款")
    @ApiOperation("后台管理操作退款")
    @GetMapping("/Wait/order/Refund")
    public APIEntity orderRefund(Integer orderId){
        TOrder tOrder = itOrderService.getById(orderId);
        if(tOrder==null){
            return APIEntity.fail("退款订单不存在");
        }
        if("SFKD".equals(tOrder.getThirdName())){
            log.info("@@@@@@@@@@@@@@@@@@@@@后台操作取消订单,用户：{}",tOrder.getThirdName());
            tOrder.setOrderStatus("已取消");//订单状态修改
            tOrder.setThirdStatus("已取消");
            itOrderService.updateById(tOrder);
            itOrderService.cancelOrder("因疫情影响，暂时无法提供服务",tOrder);
        }
        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);
        }
        if("麦芽田".equals(tOrder.getOrderChannel())){
            //tOrder.setOrderStatus("已取消");//订单状态修改
            TMaltField maltField = maltFieldService.getOne(new QueryWrapper<TMaltField>().eq("shop_id",tOrder.getShopId()));
            if(tOrder.getCourierId()==null){
                maltUtils.getDeliveryChange(tOrder,null,maltField,null,"无人接单，无法配送",1);
            }else {
                TCourier courier = courierService.getById(tOrder.getCourierId());
                CourierAddressVo cuv =redisUtil.get(KeyConst.REDIS_COURIER_ADDRESS +courier.getCourierId(), CourierAddressVo.class);
                log.info("麦芽田订单取消查询骑手缓存信息：{}",cuv);
                if(cuv == null){
                    maltUtils.getDeliveryChange(tOrder,courier.getCourierName(),maltField,null,"商家取消",3);
                }else {
                    maltUtils.getDeliveryChange(tOrder,courier.getCourierName(),maltField,cuv.getAddress(),"商家取消",3);
                }
            }
            return APIEntity.success("麦芽田订单已取消成功！");
        }
        return APIEntity.success(refund);
    }

    /**
     *支付宝与微信订单业务退款接口
     * @param
     * @return
     * @throws AlipayApiException
     * @throws IOException
     */
    @InitLog(value = "异常业务订单退款",action = "退款")
    @ApiOperation("支付宝与微信异常订单业务退款接口")
    @GetMapping("/aliAndWinRefund")
    public APIEntity aliAndWinRefund(Integer exceptionId, Integer orderId, Integer userId){
        TOrder tOrder = itOrderService.getById(orderId);
        if(tOrder==null){
            //更新异常处理结果
            TOrderExceptionEntity exceptionEntit = orderExceptionService.getById(exceptionId);
            exceptionEntit.setEndWay("订单已删除，自动处理");
            exceptionEntit.setStatus("处理完成");
            exceptionEntit.setEndTime(LocalDateTime.now());
            exceptionEntit.setEndUser(userId==null?getLoginUser().getUserId():userId);
            exceptionEntit.updateById();
            return APIEntity.success("无效的记录，该订单已被删除");
        }
        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);
        }
        /*for(TPay pay : tPays){
            if("微信".equals(pay.getPayChannel())){
                refund = refundService.wxCancel("0.00",tOrder,pay);
            }
            if("支付宝".equals(pay.getPayChannel())){
                refund = refundService.aliCancel("0.00",tOrder,pay);
            }
        }*/
        /*TPay tPay = payService.getOne(new QueryWrapper<TPay>().eq("pay_id",tOrder.getPayId()));
        if(tPay == null){
            return APIEntity.fail("该订单支付信息不存在,请检查该订单是否已经支付");
        }
        TRefund refund=null;
        if(tPay.getPayWay().equals("支付宝")){
            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());
            }
            if("Y".equals(response.getFundChange())){
                refund = refundService.tRefund(response,tOrder,null,tPay);
            }
        }
        if(tPay.getPayWay().equals("微信")){
            wxPayUtil payUtil = new wxPayUtil();
            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.wxUpdate(rs,tOrder,tPay,"业务订单退款");
                log.info("申请退款成功");
            } else {
                return APIEntity.fail(rs.get("result_code"));
            }
        }*/
        TOrderExceptionEntity exceptionEntit = orderExceptionService.getById(exceptionId);
        exceptionEntit.setEndWay("订单退款");
        exceptionEntit.setStatus("处理完成");
        exceptionEntit.setEndTime(LocalDateTime.now());
        exceptionEntit.setEndUser(userId==null?getLoginUser().getUserId():userId);
        exceptionEntit.updateById();
        itOrderService.updateById(tOrder.setOrderStatus("已取消"));
        //itOrderService.cancelOrder("系统以为您退款，如有疑问请联系客服",tOrder);
        return APIEntity.success(refund);
    }


    /**
     * 入驻缴费退款
     *支付宝派送员退款接口
     * @param
     * @return
     * @throws AlipayApiException
     * @throws IOException
     */
    @InitLog(value = "入驻缴费退款",action = "退款")
    @ApiOperation("支付宝派送员退款接口")
    @GetMapping("/courier/Refund")
    public APIEntity courierRefund(Integer courierId){
        log.info("退入驻缴费的配送员：[{}]",courierId);
        TCourier courier = courierService.getById(courierId);
        TCourierPay tPay = courierPayService.getOne(new QueryWrapper<TCourierPay>().eq("pay_num",courier.getPayNum()));
        if(courier == null){
            return APIEntity.fail("该派送员不存在,请核查");
        }
        if(courier.getCourierPayStatus().equals("未缴费")){
            return APIEntity.fail("该派送员未缴费,无法退款");
        }
        if(courier.getCourierPayStatus().equals("已退款")){
            return APIEntity.fail("该派送员已退款,请不要重复退款");
        }
        if(tPay == null){
            return APIEntity.fail("该订单支付信息不存在");
        }
        TRefund refund=null;
        AlipayTradeRefundResponse response = AliPay.refund(courier.getPayNum(),courier.getCourierSettledMoney().toString(),tPay.getPayChannelNum(),"退押金",String.valueOf(System.currentTimeMillis()));
        if(!"10000".equals(response.getCode())){
            log.info("业务处理错误！ "+response.getSubMsg());
        }
        if("Y".equals(response.getFundChange())){
            refund = refundService.courierTRefund(response,null,courier,tPay);
        }
        return APIEntity.success(refund);
    }


}
