package com.hzs.third.pay.controller.notify;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huifu.adapay.core.util.AdapaySign;
import com.hzs.common.core.constant.MagicNumberConstants;
import com.hzs.common.core.enums.EPayChannel;
import com.hzs.common.core.enums.EYesNo;
import com.hzs.common.core.exception.base.BaseException;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.domain.third.pay.TOnlineCard;
import com.hzs.third.pay.config.AdaPayConfig;
import com.hzs.third.pay.constants.AdaPayConstants;
import com.hzs.third.pay.service.IPayService;
import com.hzs.third.pay.service.ITOnlineCardService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 汇付支付回调
 */
@Slf4j
@RestController
@RequestMapping("/ada")
public class AdaPayNotifyController {

    @Autowired
    private AdaPayConfig adaPayConfig;
    @Autowired
    private IPayService iPayService;
    @Autowired
    private ITOnlineCardService itOnlineCardService;

    /**
     * 支付回调
     *
     * @param request
     */
    @PostMapping("/notify")
    public String payNotify(HttpServletRequest request) {
        try {
            // 返回数据data
            String data = request.getParameter("data");
            // 返回验签sign
            String sign = request.getParameter("sign");

            log.info("汇付支付回调 data： {}", data);
            log.info("汇付支付回调 sign： {}", sign);

            if (AdapaySign.verifySign(data, sign, adaPayConfig.getPublicKey())) {
                // 验证通过
                // 返回数据map
                HashMap<String, String> dataMap = JSONUtil.parseObj(data).toBean(HashMap.class);

                if (AdaPayConstants.SUCCESS.equals(dataMap.get("status"))) {
                    // 交易成功
                    // 汇付交易流水号
                    String payNumber = dataMap.get("id");
                    // 支付完成时间
                    Date payTime = DateUtils.parseDateOne(dataMap.get("created_time"), DateUtils.YAMMERERS);
                    // 支付扩展类型
                    String type = dataMap.get("description");

                    // 回调订单编号
                    String thirdOrderCode = dataMap.get("order_no");
                    // 订单编号
                    String orderCode = thirdOrderCode;
                    // 处理订单号以及扩展类型
                    if (thirdOrderCode.indexOf("-") > 0) {
                        // 带有分隔，需要处理
                        orderCode = thirdOrderCode.split("-")[0];
                    }
                    // 订单金额
                    BigDecimal payMoney = new BigDecimal(dataMap.get("pay_amt"));

                    // 支付后续业务处理
                    if (iPayService.notifyHandle(type, orderCode, thirdOrderCode, payNumber, payTime, payMoney, EPayChannel.ADAPAY, "")) {
                        return "";
                    }
                } else {
                    log.error("汇付支付回调状态异常: {}", dataMap.get("error_msg"));
                }
            } else {
                log.error("汇付支付回调签名验证失败");
            }
        } catch (Exception e) {
            log.error("汇付支付回调处理异常", e);
        }
        throw new BaseException("汇付支付回调处理失败");
    }

    /**
     * 绑卡回调
     *
     * @param request
     */
    @PostMapping("/fast-notify")
    public String fastNotify(HttpServletRequest request) {
        try {
            // 返回数据data
            String data = request.getParameter("data");
            // 返回验签sign
            String sign = request.getParameter("sign");

            log.info("汇付快捷绑卡回调！ data： {}", data);
            log.info("汇付快捷绑卡回调！ sign： {}", sign);

            if (AdapaySign.verifySign(data, sign, adaPayConfig.getPublicKey())) {
                // 验证通过
                // 返回数据map
                HashMap<String, String> dataMap = JSONUtil.parseObj(data).toBean(HashMap.class);

                if (AdaPayConstants.SUCCESS.equals(dataMap.get("status"))) {
                    // 处理成功
                    // 绑卡ID
                    String bindId = dataMap.get("apply_id");

                    // 查询绑定数据
                    QueryWrapper<TOnlineCard> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("CUSTOMER_NUM", adaPayConfig.getAppId());
                    queryWrapper.eq("BIND_ID", bindId);
                    queryWrapper.orderByDesc("PK_ID");
                    List<TOnlineCard> list = itOnlineCardService.list(queryWrapper);
                    if (CollectionUtil.isNotEmpty(list)) {
                        TOnlineCard tOnlineCard = list.get(0);
                        // 是、否 与现用的统一规则不一致，此处直接写死
                        if (0 == tOnlineCard.getBindStatus()) {
                            // 未绑定状态，则需要更新绑定信息
                            tOnlineCard.setBindStatus(1);
                            tOnlineCard.setBankName(dataMap.get("bank_name"));
                            tOnlineCard.setThirdInfo(dataMap.get("token_no"));
                            tOnlineCard.setPkModified(MagicNumberConstants.PK_ADMIN);
                            tOnlineCard.setModifiedTime(new Date());
                            if (itOnlineCardService.updateBankInfo(tOnlineCard) > 0) {
                                return "";
                            } else {
                                log.error("汇付快捷绑卡回调入库失败");
                            }
                        } else {
                            return "";
                        }
                    } else {
                        log.error("汇付快捷绑卡回调未找到绑定记录");
                    }
                } else {
                    log.error("汇付快捷绑卡回调状态异常");
                }
            } else {
                log.error("汇付快捷绑卡回调签名验证失败");
            }
        } catch (Exception e) {
            log.error("汇付快捷绑卡回调处理异常", e);
        }
        throw new BaseException("汇付快捷绑卡回调处理失败");
    }

    /**
     * 解绑回调
     *
     * @param request
     * @return
     */
    @PostMapping("/un-bind-notify")
    public String unBindNotify(HttpServletRequest request) {
        try {
            // 返回数据data
            String data = request.getParameter("data");
            // 返回验签sign
            String sign = request.getParameter("sign");

            log.info("汇付快捷解绑回调！ data： {}", data);
            log.info("汇付快捷解绑回调！ sign： {}", sign);

            if (AdapaySign.verifySign(data, sign, adaPayConfig.getPublicKey())) {
                // 验证通过
                // 返回数据map
                HashMap<String, String> dataMap = JSONUtil.parseObj(data).toBean(HashMap.class);

                if (AdaPayConstants.SUCCESS.equals(dataMap.get("status"))) {
                    // 处理成功
                    // 解绑银行卡
                    itOnlineCardService.unBindBank(dataMap.get("order_no"), MagicNumberConstants.PK_ADMIN, adaPayConfig.getAppId());

                    return "";
                } else {
                    log.error("汇付快捷解绑回调状态异常");
                }
            } else {
                log.error("汇付快捷解绑回调签名验证失败");
            }
        } catch (Exception e) {
            log.error("汇付快捷解绑回调处理异常", e);
        }
        throw new BaseException("汇付快捷解绑回调处理失败");
    }

}
