package com.cweb.controller.notify;

import com.alibaba.fastjson.JSONObject;
import com.cweb.controller.BsDiscountUserController;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.pay.util.SignatureUtil;
import com.hfkj.common.utils.DateUtil;
import com.hfkj.common.utils.HttpsUtils;
import com.hfkj.common.utils.RandomUtils;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.entity.*;
import com.hfkj.model.ResponseData;
import com.hfkj.model.UserSessionObject;
import com.hfkj.model.order.OrderChildModel;
import com.hfkj.openapi.model.response.OrderRefundNotifyModel;
import com.hfkj.openapi.service.ApiGasOrderService;
import com.hfkj.service.agent.BsAgentApiAccountService;
import com.hfkj.service.agent.BsAgentApiParamService;
import com.hfkj.service.gas.BsGasOrderAuditService;
import com.hfkj.service.gas.BsGasOrderService;
import com.hfkj.service.order.BsOrderChildService;
import com.hfkj.service.order.BsOrderRefundService;
import com.hfkj.service.order.BsOrderService;
import com.hfkj.service.order.BsOrderSettleService;
import com.hfkj.sysenum.gas.GasOrderAuditStatusEnum;
import com.hfkj.sysenum.gas.GasOrderCreateType;
import com.hfkj.sysenum.gas.OrderOilStatus;
import com.hfkj.sysenum.order.OrderRefundStatusEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @className: NewLink2NotifyController
 * @author: HuRui
 * @date: 2025/12/15
 **/
@Controller
@RequestMapping(value = "/newLink2Notify")
@Api(value = "油站渠道能链2 通知")
public class NewLink2NotifyController {
    private static Logger log = LoggerFactory.getLogger(NewLink2NotifyController.class);

    @Resource
    private BsOrderRefundService orderRefundService;
    @Resource
    private BsGasOrderService gasOrderService;
    @Resource
    private BsOrderSettleService orderSettleService;
    @Resource
    private BsOrderService orderService;
    @Resource
    private BsAgentApiAccountService agentApiAccountService;
    @Resource
    private BsAgentApiParamService agentApiParamService;
    @Resource
    private BsOrderChildService orderChildService;
    @Resource
    private BsGasOrderAuditService gasOrderAuditService;

    @RequestMapping(value = "/orderComplete", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "订单完成通知")
    public Object orderComplete(@RequestBody JSONObject body) {
        try {
            System.out.println("订单完成通知参数：" + body.toJSONString());


            Map<String,Object> retMap = new HashMap<>();
            retMap.put("data", "");
            retMap.put("code", "200");
            retMap.put("msg", "请求成功");
            return retMap;

        } catch (Exception e) {
            return ResponseMsgUtil.exception(e);
        }
    }


    @RequestMapping(value = "/refundResult", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "退款结果")
    public Object refundResult(@RequestBody JSONObject body) {
        try {
            System.out.println("退款结果通知参数：" + body.toJSONString());
            // 查询加油订单
            BsGasOrder gasOrder = gasOrderService.getDetailByChannelOrderNo(body.getString("orderNo"));
            if (gasOrder != null && OrderOilStatus.STATUS5.getNumber().equals(gasOrder.getStatus())) {
                // 查询退款订单
                BsOrderRefund refund = orderRefundService.getRefundByOrderNo(gasOrder.getOrderNo());
                if (refund == null) {
                    if (gasOrder.getCreateType().equals(GasOrderCreateType.TYPE1.getNumber())) {
                        // 查询交易订单
                        BsOrder order = orderService.getOrder(gasOrder.getOrderNo());
                        // 查询交易结算
                        BsOrderSettle orderSettle = orderSettleService.getData(order.getOrderNo());
                        // 子交易订单
                        OrderChildModel orderChild = orderChildService.getDetail(gasOrder.getOrderChildNo());
                        // 创建退款订单
                        refund = new BsOrderRefund();
                        refund.setMerId(gasOrder.getMerId());
                        refund.setMerNo(gasOrder.getMerNo());
                        refund.setOrderNo(orderChild.getOrderNo());
                        refund.setOrderChildNo(orderChild.getChildOrderNo());
                        refund.setUserId(gasOrder.getUserId());
                        refund.setUserPhone(gasOrder.getUserPhone());
                        // 退款订单号 退款标识：R + 时间 + 随机3位数字
                        refund.setRefundOrderNo(body.getString("refundNo"));
                        refund.setRefundPayChannel(order.getPayChannel());
                        refund.setRefundPayType(order.getPayType());
                        refund.setRefundPrice(orderChild.getSurplusRefundPrice());
                        refund.setRefundIntegral(orderChild.getSurplusRefundIntegral());
                        refund.setRefundRemark(body.getString("refundReason"));
                        refund.setRefundStatus(OrderRefundStatusEnum.status1.getCode());
                        refund.setAccountMerchantNo(orderSettle.getSettleMerNo());
                        refund.setAccountMerchantKey(orderSettle.getSettleMerKey());
                        refund.setCreateType(GasOrderCreateType.TYPE1.getNumber());
                        orderRefundService.editData(refund);
                    } else {
                        // 创建退款订单
                        refund = new BsOrderRefund();
                        refund.setMerId(gasOrder.getMerId());
                        refund.setMerNo(gasOrder.getMerNo());
                        refund.setOrderNo(gasOrder.getOrderNo());
                        refund.setUserPhone(gasOrder.getUserPhone());
                        refund.setRefundOrderNo(body.getString("refundNo"));
                        refund.setRefundPayType(gasOrder.getPayType());
                        // 全部退款
                        refund.setRefundPrice(gasOrder.getGasRefuelPrice());
                        refund.setRefundIntegral(0L);
                        refund.setRefundRemark(body.getString("refundReason"));
                        refund.setRefundStatus(OrderRefundStatusEnum.status1.getCode());
                        refund.setCreateType(GasOrderCreateType.TYPE2.getNumber());
                        orderRefundService.editData(refund);
                    }
                }
                if (refund != null && OrderRefundStatusEnum.status1.getCode() == refund.getRefundStatus()) {
                    // 订单所有状态 0-待支付 1-已支付 2-退款中  4-订单取消 5-已退款 7-退款失败
                    if (body.getInteger("orderStatus") == 5) {
                        refund.setFinishTime(body.getDate("refundTime"));
                        refund.setRefundStatus(OrderRefundStatusEnum.status2.getCode());
                        orderRefundService.editData(refund);

                        gasOrder.setStatus(OrderOilStatus.STATUS4.getNumber());
                        gasOrder.setRefundTime(body.getDate("refundTime"));
                        gasOrderService.updateGasOrder(gasOrder);

                        // 退款审核数据
                        BsGasOrderAudit gasOrderAudit = gasOrderAuditService.getDetailByOrderNo(refund.getOrderNo(), GasOrderAuditStatusEnum.type4);
                        if (gasOrderAudit != null) {
                            gasOrderAudit.setStatus(GasOrderAuditStatusEnum.type2.getCode());
                            gasOrderAuditService.editData(gasOrderAudit);
                        }

                        if (gasOrder.getCreateType().equals(GasOrderCreateType.TYPE1.getNumber())) {
                            orderRefundService.refundMoney(refund);

                        } else if (gasOrder.getCreateType().equals(GasOrderCreateType.TYPE2.getNumber())) {
                            try {
                                // 代理商退款退款
                                agentApiAccountService.refund(gasOrder.getAgentId(),gasOrder.getGasRefuelPrice(), refund);

                                // 推送代理商
                                if (gasOrder.getCreateType().equals(GasOrderCreateType.TYPE2.getNumber())) {
                                    // 代理参数
                                    BsAgentApiParam apiParam = agentApiParamService.getParam(gasOrder.getAgentId());
                                    if (apiParam != null && StringUtils.isNotBlank(apiParam.getOrderRefundNotify())) {
                                        // 通知数据
                                        OrderRefundNotifyModel refundNotify = new OrderRefundNotifyModel();
                                        refundNotify.setOrderNo(refund.getOrderNo());
                                        refundNotify.setChannelType(gasOrder.getChannelType());
                                        refundNotify.setChannelOrderNo(gasOrder.getChannelOrderNo());
                                        refundNotify.setRefundResult(refund.getRefundStatus() == 2 ? true : false);
                                        refundNotify.setRefundFailReason(refund.getRefundFailReason());
                                        refundNotify.setSign(SignatureUtil.createSign(refundNotify, apiParam.getAppSecret()));
                                        HttpsUtils.doApiPost(apiParam.getOrderRefundNotify(), JSONObject.parseObject(JSONObject.toJSONString(refundNotify), JSONObject.class));
                                    }
                                }
                            } catch (Exception e) {

                            }
                        }

                    }  else if (body.getInteger("orderStatus") == 7) {
                        refund.setRefundStatus(OrderRefundStatusEnum.status3.getCode());
                        refund.setRefundFailReason(body.getString("refundFailReason"));
                        orderRefundService.editData(refund);

                        gasOrder.setStatus(OrderOilStatus.STATUS6.getNumber());
                        gasOrderService.updateGasOrder(gasOrder);

                        // 退款审核数据
                        BsGasOrderAudit gasOrderAudit = gasOrderAuditService.getDetailByOrderNo(refund.getOrderNo(), GasOrderAuditStatusEnum.type4);
                        if (gasOrderAudit != null) {
                            gasOrderAudit.setStatus(GasOrderAuditStatusEnum.type5.getCode());
                            gasOrderAudit.setRejectRemark(body.getString("refundFailReason"));
                            gasOrderAuditService.editData(gasOrderAudit);
                        }

                        // 推送代理商
                        if (gasOrder.getCreateType().equals(GasOrderCreateType.TYPE2.getNumber())) {
                            // 代理参数
                            BsAgentApiParam apiParam = agentApiParamService.getParam(gasOrder.getAgentId());
                            if (apiParam != null && StringUtils.isNotBlank(apiParam.getOrderRefundNotify())) {
                                // 通知数据
                                OrderRefundNotifyModel refundNotify = new OrderRefundNotifyModel();
                                refundNotify.setOrderNo(refund.getOrderNo());
                                refundNotify.setChannelType(gasOrder.getChannelType());
                                refundNotify.setChannelOrderNo(gasOrder.getChannelOrderNo());
                                refundNotify.setRefundResult(refund.getRefundStatus() == 2 ? true : false);
                                refundNotify.setRefundFailReason(refund.getRefundFailReason());
                                refundNotify.setSign(SignatureUtil.createSign(refundNotify, apiParam.getAppSecret()));
                                HttpsUtils.doApiPost(apiParam.getOrderRefundNotify(), JSONObject.parseObject(JSONObject.toJSONString(refundNotify), JSONObject.class));
                            }
                        }
                    }
                }
            }
            Map<String,Object> retMap = new HashMap<>();
            retMap.put("data", "");
            retMap.put("code", "200");
            retMap.put("msg", "请求成功");
            return retMap;

        } catch (Exception e) {
            return ResponseMsgUtil.exception(e);
        }
    }

}
